依次播放网址中的音频

时间:2019-04-20 10:24:07

标签: android android-mediaplayer

我要一个接一个地自动播放/流式传输音频。

这是我尝试过的:

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
        }
    }
});

当我单击 backtoback 命名按钮时,播放了我的第一个音频URL,但是无法播放该URL中的第二个音频。

1 个答案:

答案 0 :(得分:0)

更改了这部分代码

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

工作了。