Android停止响起

时间:2016-09-07 18:52:14

标签: android

我正在写一个警报应用。收到提醒时,我想停止所有当前声音(如音乐)并播放我的提示音。在用户完成某项操作并且活动将关闭后,之前的声音应该继续。

就像有人打电话给你一样。我怎样才能实现这种行为?

2 个答案:

答案 0 :(得分:2)

您可以申请audio focus。完成自己的音频后,放弃音频焦点,以便其他应用可以再次开始播放声音。您将收到其他请求音频焦点的应用程序的通知,从而能够暂停和恢复您自己的声音。

请求音频焦点:

AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);

// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                                 // Use the music stream.
                                 AudioManager.STREAM_MUSIC,
                                 // Request permanent focus.
                                 AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    am.registerMediaButtonEventReceiver(RemoteControlReceiver);
    // Start playback.
}

答案 1 :(得分:2)

在Julius Skripkauskas的帮助下'回答我使用以下代码:

开始提示音:

private void playSound(){
try{
            Log.d(TAG, "request audio focus");
            this.am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
            int result=this.am.requestAudioFocus(afListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);
            if(result==AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
                Log.d(TAG, "audio focus granted");
                this.player=new MediaPlayer();
                this.player.setOnPreparedListener(new OnPreparedListener(){

                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();                 
                    }});
                this.player.setOnCompletionListener(new OnCompletionListener(){

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        am.abandonAudioFocus(afListener);
                    }});
                this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                this.player.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound ));
                this.player.prepareAsync();
            }
        }catch(Exception e){
            Log.e(TAG, "error playing music." + e.getMessage(), e);
        }
}

听众: 我只是停止声音,因为我只会在获得焦点后播放声音。如果声音会被其他应用程序中断,那么这并不重要......

private AudioManager.OnAudioFocusChangeListener afListener = new AudioManager.OnAudioFocusChangeListener(){

@Override
public void onAudioFocusChange(int focusChange) {
    Log.d(TAG, "audio focus changed" + Integer.toString(focusChange));
    if(player==null){
        // we don't play audio
        return;
    }           
    player.stop();
}};

重要的是要考虑将OnCompletionListener添加到播放器的位置am.abandonAudioFocus(afListener),以便在播放声音后立即释放音频焦点。