在我的音乐播放器中,如果一首歌曲已经在播放,并且用户单击另一首歌曲,则该歌曲也会开始播放。换句话说,一次播放多首歌曲确实很烦人。我一次想要一首歌。这意味着,如果一首歌曲已经在播放,并且用户单击另一首歌曲,则前一首歌曲将停止播放,而被点击的歌曲将播放。
java代码
public void onItemClick(final Button b, View view, final SongInfo obj, int position) {
if(b.getText().equals("Stop")){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
b.setText("Play");
}
else {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
Log.d("Prog", "run: " + mediaPlayer.getDuration());
}
});
b.setText("Stop");
}catch (Exception e){}
}
};
myHandler.postDelayed(runnable,100);
}
}
});
checkUserPermission();
Thread t = new runThread();
t.start();
}
//Thread method for seek bar
public class runThread extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Runwa", "run: " + 1);
if (mediaPlayer != null) {
seekBar.post(new Runnable() {
@Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
});
Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
}
}
}
}
答案 0 :(得分:0)
if("STOP".equalsIgnoreCase(b.getText()) {
mediaPlayer.stop() // stop the media player
mediaPlayer.reset() // reset media player for re-use
b.setText("Play"); // to re-play song
} else {
// use the same instance of media-player if want to play single song at a time
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepare(); // can use prepareAsync() also
mediaPlayer.start();
b.setText("Stop");
}
要一次只播放一首歌曲,则必须始终使用mediaPlayer
对象的相同实例。 (请参阅内嵌评论)