只有当特定活动开始时,MediaPlayer才会继续播放



我的活动有一个背景音乐的Mediaplayer。我想在新活动开始时暂停它并重置它,在活动结束时停止它。

我是这样做的:

@Override
protected void onResume() {
        if(!continiue){
            continiue=true;
    try{
        if (m != null) {
            m=new MediaPlayer();
                m.reset();
                m = MediaPlayer.create(this, R.raw.menu);
                m.start();
        m.setLooping(true);
        }
        else{
            m.start();
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
    super.onResume();
        }
}
@Override
protected void onStop() {
    try{
    if(m!=null){
        m.stop();
        m.release();
    }
    }
    catch(Exception e){
    }
    super.onStop();
} 
@Override
protected void onPause() {
    try{
    if(m.isPlaying()){
        m.pause();
    }
    }
    catch(Exception e){
    }
    super.onPause();
}

这很好。现在我想添加另一个活动,但我希望只有当这个特定活动打开时,音乐才能继续播放。我该怎么做?

只为音乐播放创建一个单独的类,并从Activities中对其进行规则化。类似这样的东西:

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
public class BackgroundMusicPlayer {
    private static MediaPlayer mp = null;
    private static int playingResId;
    public static boolean isSoundTurnedOff;
    private static boolean isPaused;
    /** Stop old sound and start new one */
    public static void play(Context context, int resIdToPlay) {
        if (isSoundTurnedOff || context==null)
            return;
        if (mp != null && playingResId==resIdToPlay) {
            if (isPaused)
                mp.start();
            isPaused = false;
            return;
        }
        stop();
        Intent i = new Intent("com.android.music.musicservicecommand");
        i.putExtra("command", "pause");
        context.sendBroadcast(i);
        playingResId = resIdToPlay;
        mp = MediaPlayer.create(context, resIdToPlay);
        if (mp != null) {
            mp.setLooping(true);
            mp.start();
        } else 
            Log.e("BackgroundMusicPlayer","Cant create MediaPlayer. MediaPlayer.create(context: "+context+", resIdToPlay: "+resIdToPlay+") returns null");

    }
    /** Stop the music */
    public static void stop() {
        if (mp != null) {
            isPaused = false;
            playingResId = 0;
            mp.stop();
            mp.release();
            mp = null;
        }
    }
    public static void pause() {
        if (mp != null){
            mp.pause();
            isPaused = true;
        }
    }
    public static void resume() {
        if (mp != null && isPaused){
            mp.start();
            isPaused = false;
        }
    }
}

最新更新