我已经写了一个mediaPlayer应用程序,并且mediaplayer.setOnCompletionListener
在歌曲完成之前被调用,并且每首歌都会继续播放...它会继续播放到下一首歌,直到它到达最后一首歌播放列表中的歌曲...请帮忙
这是我的代码:
tracksListViewForSpeakers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Track track = playlistContents.get(position);
String filepath = track.getFilePath();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(filepath);
mediaPlayer.start();
// mediaPlayer.setVolume(0, 0);
} catch (IOException e) {
e.printStackTrace();
for(int i=0;i<4;i++)
System.out.println("MediaPlayer Exception");
}
}
});
完成监听器
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
onNextClicked(mp);
}
});
OnNextClickedMethod
public void onNextClicked(MediaPlayer mp){
int val = myModel.getCurrentPlayingIndex();
val=val+1;
Track track = currentPlayList.get(val);
String filepath = track.getFilePath();
if (mp.isPlaying()) {
mp.stop();
}
mp.reset();
try {
mp.setDataSource(filepath);
mp.start();
// mediaPlayer.setVolume(0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
使用此功能在完成时播放下一首歌曲
@Override
public void onCompletion(MediaPlayer arg0) {
if (isRepeat) {
// repeat is on play same song again
playSong(currentSongIndex);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
然后playong方法就是这样
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
或者您可以看到本教程并实现此
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
答案 1 :(得分:2)
试试这个
//set path
mediaPlayer.setDataSource("yourFilePath");
mediaPlayer.setOnPrepareListener(new OnPrepareListener(MediaPlayer mediaPlayer) {
mediaPlayer.start();
});
mediaPlayer.prepareAsync();
如果没有start()
,请不要致电prepareAsync();
希望它能解决你的问题..