java – Play audio on button click

Question:

I have a collection that stores audio titles

songs = new ArrayList<>();
songs.add("song_1.ogg");
songs.add("song_2.ogg");
songs.add("song_3.ogg");
songs.add("song_4.ogg");
songs.add("song_5.ogg");
songs.add("song_6.ogg");

There is a method that plays audio depending on what value is passed.

private void playSong(int i) {
    String mSong = songs.get(i);
    try {
        AssetFileDescriptor afd = this.getAssets().openFd("sounds/songs/" + mSong);
        mp = new MediaPlayer();
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        mp.setLooping(false);
        mp.prepare();
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
            }
        });
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

There is a button, by clicking on which you need to play audio like this: Pressed once starts playing audio from the song_1.ogg collection, pressed a second time the first one stops playing audio song_2.ogg, etc. to audio song_6.ogg. If you click again, then again play the audio song_1.ogg, etc.

How to implement it? Just tell me the logic. And then I did this, and several audios start playing for me if I press the button several times

counter

private int counter = 0;

block case

case R.id.btnMusic:
    if (counter == 0) {
        play(0);
    } else if (counter == 1) {
        mp.release();
        play(1);
    } else if (counter == 2) {
        mp.release();
        play(2);
    } else if (counter == 3) {
        mp.release();
        play(3);
    } else if (counter == 4) {
        mp.release();
        play(4);
    } else if (counter == 5) {
        mp.release();
        play(5);
    }
    break;

The method itself

private void play(int i) {
    counter = i;
    String mSong = songs.get(counter);
    try {
        AssetFileDescriptor afd = this.getAssets().openFd("sounds/songs/" + mSong);
        mp = new MediaPlayer();
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        mp.setLooping(false);
        mp.prepare();
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
            }
        });
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Answer:

Paste in the play() method, something like:

if(mp.isPlaying()) {
   mp.stop();
   mp.reset();
}

And the player itself must be created 1 time, otherwise you create a new instance of the player with each call.

Scroll to Top