2013-05-21 129 views
0

我试图播放在整个应用程序中运行的背景声音。在这里,我有3个活动,并在主要活动启动时开始发声。 我想要实现这些: 1)在整个应用程序中连续播放bg声音,无论任何活动加载。
2)当用户点击声音关闭按钮时关闭声音。 3)当应用程序关闭时停止声音。在Android中播放背景声音

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

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

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

回答

0

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

Binding to a Started Service

服务文档中所讨论的,您可以创建一个服务,既是开始和束缚。也就是说,可以通过调用startService()来启动该服务,该服务允许服务无限期运行,并允许客户端通过调用bindService()来绑定到服务。

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

+0

谢谢。我从http://marakana.com/forums/android/examples/60.html获得详细信息 – Amrit