0

我正在尝试播放在整个应用程序中运行的背景声音。这里我有 3 个活动,当 MAIN 活动启动时,声音就开始了。我想实现这些:1)无论活动加载如何,在整个应用程序中连续播放 bg 声音。
2)当用户单击声音关闭按钮时关闭声音。3)当应用程序关闭时停止声音。

到目前为止,我已经尝试过这段代码来启动声音,但即使应用程序关闭,它也会继续播放。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    audioPlayer();
}

    boolean isPlayingSound = true;
public void onClickSound(View view) {
    final Button btn1 = (Button) findViewById(R.id.button3);

    if(isPlayingSound){ 
        btn1.setBackgroundResource(R.drawable.sound00);
        isPlayingSound=false;
        audioPlayer(false);/*Sound doesn't stops here*/
    } 
    else{ 
        btn1.setBackgroundResource(R.drawable.sound11);
        isPlayingSound=true;
        audioPlayer(true);
    }     
}

public void audioPlayer(boolean status){  

    MediaPlayer mp = MediaPlayer.create(this, R.raw.bg);
    if(status) {
        mp.start();
    }
    else {
        mp.stop();
    }
}

任何人都可以在这里看看并帮助我。感谢帮助!!

4

1 回答 1

0

您可以播放音频移动到服务。你可以参考 ASOP 音乐代码或看

绑定到已启动的服务

正如服务文档中所讨论的,您可以创建一个已启动和绑定的服务。即服务可以通过调用startService()来启动,这样可以让服务无限期地运行,也可以让客户端通过调用bindService()来绑定服务。

如果您确实允许启动和绑定您的服务,那么当服务已启动时,系统不会在所有客户端解除绑定时销毁该服务。相反,您必须通过调用 stopSelf() 或 stopService() 显式停止服务。

于 2013-05-21T06:08:40.790 回答