首页 > 解决方案 > 当我单击android中的按钮时,我想一个接一个地播放音频

问题描述

ArrayList<String> videolist = new ArrayList<>();
videolist.add("http://muurl.com/abc/song1.mp3");
videolist.add("http://muurl.com/abc/song2.mp3");
videolist.add("http://muurl.com/abc/song3.mp3");

我已将音频链接存储在数组列表中。当我单击按钮时,我想一个接一个地播放该音频,当我单击按钮时,第二次音频应该从第一个音频链接开始

标签: javaandroidandroid-mediaplayer

解决方案


结合OnCompletionListener查看MediaPlayer类:

你会做这样的事情:

int playListPos = 0; // declare this outside the button click probably as a global variable (so we can access it and increment in the on click listener of the button

// the below code should go inside the button click
String url = videolist.get(playListPos); // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
    AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .build()
);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
    // this will be called every time a file is finished playing
    if (videolist.size() < playListPos) { // let's see if there is more files to play
        mediaPlayer.setDataSource(videolist.get(playlistPos));
        mediaPlayer.prepare();
        mediaPlayer.start();
        playListPos++;
    } else {
         // we played until the end. reset to 0 for when button is clicked again to restart from the beginning
         playListPos = 0;
   }
});
mediaPlayer.start();

推荐阅读