gpt4 book ai didi

java - MediaPlayer 仅在特定 Activity 开始时继续播放

转载 作者:行者123 更新时间:2023-12-01 11:41:32 24 4
gpt4 key购买 nike

我有一个用于我的 Activity 的背景音乐媒体播放器。我想在新 Activity 开始时暂停它并重置它,并在 Activity 销毁时停止它。

我就是这样做的:

@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();
}

这工作得很好。现在我想添加另一个 Activity ,但我希望音乐仅在该特定 Activity 打开时继续播放。我怎样才能做到这一点?

最佳答案

创建一个仅用于音乐播放的单独类,并从“Activity ”中对其进行规则。像这样的事情:

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;
}
}

}

关于java - MediaPlayer 仅在特定 Activity 开始时继续播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29489212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com