我是 android 应用程序开发的新手,我认为这可能是一个非常简单的问题,但我无法弄清楚如何做我想做的事......
我有一个简单的应用程序,可以在按下按钮时播放声音。播放声音后,我希望应用程序将音频返回到应用程序启动之前正在播放的任何内容(例如,如果音乐应用程序正在播放,声音应该在播放时中断音乐,然后返回控制并恢复音乐播放。我尝试使用 setOnCompletionListener 方法,但没有任何乐趣。
这是代码:
public class MainActivity extends Activity implements OnClickListener{
public MediaPlayer mp = null;
public ImageButton playm = null;
public AudioManager audioManager = null;
/** called when activity first created */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
//Sigh Button
playm = (ImageButton) findViewById(R.id.sighButton);
playm.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v==playm){
OnAudioFocus onAudioFocus=new OnAudioFocus(this);
audioManager.requestAudioFocus(onAudioFocus, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
playSighSound();
}
}
public void playSighSound(){
mp = MediaPlayer.create(this, R.raw.ohboy);
try {
mp.start();
mp.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp){
mp.release();
}
});
} catch (IllegalArgumentException e){
e.printStackTrace();
} catch (IllegalStateException e){
e.printStackTrace();
}
}
}
class OnAudioFocus implements AudioManager.OnAudioFocusChangeListener{
MainActivity onAudioFocus;
public OnAudioFocus(MainActivity onAudioFocus){
this.onAudioFocus = onAudioFocus;
}
public void onAudioFocusChange(int focusChange) {
switch(focusChange){
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
onAudioFocus.playSighSound();
break;
}
}
}