问题描述
我有一个媒体播放器,如果有媒体播放器在播放,我希望它停止播放,然后新的媒体播放器开始播放,则每次调用此活动...这是我的音频播放器方法
I have a media player and everytime that this activity is called if there is a media player playing i want it to stop and the new media player start playing ... This is my audio player method
private void playAudio(String url) throws Exception{
mediaplayer.release();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
}
我在课程开始时初始化媒体播放器
I initialize the media player at the beginning of the class
private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);
// Getting Our Extras From Intent
Bundle names = getIntent().getExtras();
// Getting Specific Data
path = names.getString("pathkeyword");
//Start Player
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}
每次创建此类时,它都会创建一个新的媒体播放器,不会停止另一个播放器,而只是同时播放两个播放器.
Everytime this is class is created it creates a new media player doesn't stop the other one and just plays both at the same time.
推荐答案
您可能希望调查onPause
并杀死媒体播放器.问题是,一旦第二次就没有对媒体播放器的引用.结果,您开始了活动,播放了音乐,但是当您退出(例如,按HOME按钮)时,媒体播放器没有被告知要停止(它作为一个单独的线程运行).重新打开它时,它将在新线程上启动新的媒体播放器,并产生两种声音.
You may wish to look into onPause
and kill the media player then. The problem is that there is no reference to the media player once it has been made a 2nd time. As a result, you start up your activity, play the music, but when you exit (e.g. press the HOME button) the media player has not been told to stop (it runs as a separate thread). When you reopen it, it will start a new media player on a new thread, producing two sounds.
要解决此问题,请在退出时正确杀死媒体播放器.当您退出活动时,这将正确杀死媒体播放器:
To fix this, kill the media player properly when you exit. This will properly kill the media player when you quit the activity:
@Override
protected void onPause(){
super.onPause();
if(mediaplayer.isPlaying()){
try{
mediaplayer.stop();
}
catch(IllegalStateException){
Log.d("mediaplayer","Media player was stopped in an illegal state.");
}
}
}
如果您希望在活动不在前台时继续播放音乐,则需要使用Service
.
If you wish to continue the music whilst the activity is not in the foreground, you need to use a Service
.
这篇关于Mediaplayer继续播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!