我正在制作一个音乐应用程序,以提高自己的技能,并希望它使用IDocumentClient
方法自动播放歌曲。但是它只运行一次,将song1插入song2,然后将其转到song3。
我将setOnCompletionListener
放在我的setOnCompletionListener
方法上,如下所示:
onCreate
这是我的mySong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
nextSong();
}
});
方法:
nextSong()
playMusic方法,以防万一:
public void nextSong() {
ifPlaying = true; //for displaying purposes
displayPP(); //for displaying purposes
//if switch is checked, randomize songs
if (mySwitch.isChecked()) {
musicCounter = dice.nextInt(songNumbers);
Toast.makeText(getApplicationContext(), Integer.toString(musicCounter), Toast.LENGTH_SHORT).show();
mySong.reset();
playMusic();
} else {
if (musicCounter < songNumbers - 1) {
musicCounter++;
mySong.reset();
playMusic();
} else {
Toast.makeText(getApplicationContext(), "No more songs", Toast.LENGTH_SHORT).show();
}
if (test.equalsIgnoreCase("Jason Mraz")) {
displaySong(jm);
} else if (test.equalsIgnoreCase("fob")) {
displaySong(fob);
} else if (test.equalsIgnoreCase("ed")) {
displaySong(ed);
}
}
}
而且,我一直在使用nextSong();我的下一个按钮上的方法,它工作正常。所以我想知道为什么它只在setOnCompletionListener()中执行一次;方法。这是我下一个按钮的代码:
public void playMusic() {
//test is intent.putExtra to know what index was clicked on my listview
if(test.equalsIgnoreCase("Jason Mraz")) {
mySong = MediaPlayer.create(MusicClass.this, jm[musicCounter]);
displaySong(jm);
songNumbers = jm.length;
mySong.start();
} else if(test.equalsIgnoreCase("fob")) {
mySong = MediaPlayer.create(MusicClass.this, fob[musicCounter]);
displaySong(fob);
songNumbers = fob.length;
mySong.start();
} else if(test.equalsIgnoreCase("ed")) {
mySong = MediaPlayer.create(MusicClass.this, ed[musicCounter]);
displaySong(ed);
songNumbers = ed.length;
mySong.start();
}
}
答案 0 :(得分:0)
那是因为您只设置一次onCompletionListener
,然后,每当调用playMusic()
时,您就会覆盖mySong
的值,而您再也不会设置onCompletionListener
。
解决问题的一种方法是按如下方式修改playMusic()
方法:
public void playMusic() {
if(test.equalsIgnoreCase("Jason Mraz")) {
mySong = MediaPlayer.create(MusicClass.this, jm[musicCounter]);
displaySong(jm);
songNumbers = jm.length;
}else if(test.equalsIgnoreCase("fob")) {
mySong = MediaPlayer.create(MusicClass.this, fob[musicCounter]);
displaySong(fob);
songNumbers = fob.length;
}else if(test.equalsIgnoreCase("ed")) {
mySong = MediaPlayer.create(MusicClass.this, ed[musicCounter]);
displaySong(ed);
songNumbers = ed.length;
}
mySong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
nextSong();
}
});
mySong.start();
}