我在Android应用程序中使用mediaPlayer从网上流式传输MP3网址。我不只是播放1个URL,而是如何流5个URL依次播放?这是我的代码
Uri myUri = Uri.parse("https://db.tt/9nBgouRf");
final MediaPlayer sdrPlayer = new MediaPlayer();
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); //don't use prepareAsync for mp3 playback
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again", Toast.LENGTH_LONG).show();
}
play.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
sdrPlayer.start();
}
}
);
最佳答案
只需创建一个列表即可保存所有URI
设置一些类变量:
private int playlistPos = 0;
private List<Uri> myUris = new ArrayList<Uri>();
private MediaPlayer sdrPlayer = new MediaPlayer();
设置初始化歌曲的方法:
public initSong(Uri myUri) {
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); // don't use prepareAsync for mp3 playback
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again",
Toast.LENGTH_LONG).show();
}
}
然后在
onCreate()
myUris.add(Uri.parse("https://db.tt/9nBgouRf"));
// Add the others as well...
initSong(myUris.get(playlistPos);
sdrPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
playlistPos++;
initSong(myUris.get(playlistPos));
sdrPlayer.start(); // Start it as well if you wish
}
});
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sdrPlayer.start();
}
});