Search code examples
androidandroid-mediaplayer

Play audio from url one after other


I want to play/stream audio from url one after other automatically.

here what I have tried:

final String audioUrl[] = {"https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/NV.wav?alt=media", "https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/cqo.wav?alt=media"};

backtobackButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(audioUrl[currentTrack]);
            mediaPlayer.prepareAsync();

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        Log.d("Current track",currentTrack+"");
                        Log.d("audioUrl.length",audioUrl.length+"");
                        if (currentTrack < audioUrl.length) {
                            currentTrack++;
                            mediaPlayer.setDataSource(audioUrl[currentTrack]);
                            mediaPlayer.setOnCompletionListener(this);
                            mediaPlayer.start();
                        }
                        mediaPlayer.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            // make something
        }
    }
});

My first audio url gets played when I click on backtoback named button but failed to play second audio from url.


Solution

  • changed this part of code

    mediaPlayer.reset();
    mediaPlayer.setDataSource(audioUrl[currentTrack]);
    mediaPlayer.prepareAsync();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.start();
    currentTrack++;
    

    and worked.