问题描述
在我的音乐播放器中,如果一首歌曲已经在播放,并且用户点击另一首歌曲,那首歌曲也会开始播放.换句话说,同时播放多首歌曲,这真的很烦人.我一次想要一首歌.这意味着,如果一首歌曲已经在播放,并且用户点击另一首歌曲,那么上一首歌曲将停止播放,而点击的歌曲将继续播放.
In my music player if one song is already playing and if the user clicks on another song then that song also starts playing. In other words, there are multiple songs are playing at a single time this is really annoying. I want one song at a time. That means if a song is already playing and if the user clicks on another song then the previous song will gonna stop and the clicked song will gonna play.
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());
}
}
}
}
推荐答案
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
对象的相同实例.(见内嵌评论)
To play only one song at a time, you have to use same instance of mediaPlayer
object throughout. (See comments inline)
参考:媒体播放器状态图
这篇关于如何在 android studio 中一次播放一首歌曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!