我有一系列歌曲,我的应用程序在一个活动打开时随机播放歌曲但是当歌曲结束时我想播放该阵列中的另一首随机歌曲,有人可以帮忙吗?
public MediaPlayer mediaPlayer;
private int songs[];
songs = new int[] {
R.raw.track1,
R.raw.track2,
R.raw.track3,
R.raw.track4,
R.raw.track5,
R.raw.track6,
R.raw.track7,
R.raw.track8,
R.raw.track9,
R.raw.track10,
R.raw.track11,
R.raw.track12,
R.raw.track13,
R.raw.track14,
R.raw.track15,
R.raw.track16,
R.raw.track17,
};
int randomSong = new Random().nextInt(songs.length);
mediaPlayer = MediaPlayer.create(this, songs[randomSong]);
mediaPlayer.start();
答案 0 :(得分:2)
您需要设置completion listener:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
void onCompletion(MediaPlayer mp) {
// Play next song
}
});
答案 1 :(得分:2)
试试这个,你需要实现MediaPlayer.OnCompletionListener
接口
在你的活动中
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener {
private MediaPlayer mediaPlayer;
private int songs[];
private int randomSong;
private Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer.setOnCompletionListener(this);
songs = new int[]{
R.raw.track1,
R.raw.track2,
R.raw.track3,
R.raw.track4,
R.raw.track5,
R.raw.track6,
R.raw.track7,
R.raw.track8,
R.raw.track9,
R.raw.track10,
R.raw.track11,
R.raw.track12,
R.raw.track13,
R.raw.track14,
R.raw.track15,
R.raw.track16,
R.raw.track17,
};
randomSong = getRandom(songs);
mediaPlayer = MediaPlayer.create(this, songs[randomSong]);
mediaPlayer.start();
}
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
randomSong = getRandom(songs);
mediaPlayer = MediaPlayer.create(this, songs[randomSong]);
mediaPlayer.start();
}
public int getRandom(int[] array) {
return random.nextInt(array.length);
}
}
答案 2 :(得分:1)
您可以在歌曲播放完毕后使用侦听器来运行回调:
setOnCompletionListener(MediaPlayer.OnCompletionListener listener)
另外,为确保随机性,我强烈建议您每次需要随机数时不要使用新的Random
对象。相反,声明变量random
并将其用于满足您的所有随机需求。