10

当电话响起时,我正在尝试暂停媒体播放器。我使用来自 android 网站的示例代码。就像这样;

public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            // resume playback
            if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
                mMediaPlayer.setVolume(1.0f, 1.0f);
            }

            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            // Lost focus for an unbounded amount of time: stop playback and
            // release media player
            stopMediaPlayer();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            // Lost focus for a short time, but we have to stop
            // playback. We don't release the media player because playback
            // is likely to resume
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.pause();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // Lost focus for a short time, but it's ok to keep playing
            // at an attenuated level
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.setVolume(0.1f, 0.1f);
            break;
        }
    }

手机响铃时发送 AUDIOFOCUS_LOSS_TRANSIENT;没关系。当通话结束时,发送 AUDIOFOCUS_GAIN 并且播放器继续播放;这也可以。但是在发送 AUDIOFOCUS_GAIN 之后,立即发送 AUDIOFOCUS_LOSS。有什么想法为什么它会失去音频焦点?提前谢谢。

4

2 回答 2

3

可能它会帮助某人。我在项目中没有直接使用 MediaPlayer 而是通过 VideoView 时遇到了这个问题。打开文件时有以下代码

AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

因此,当您打开文件时,它会获得音频焦点,并且在使用 focusChange 触发之前设置的侦听器AudioManager.AUDIOFOCUS_LOSS

于 2015-04-17T12:04:43.073 回答
3

Two things to check: 1) Do you have a play button for instance, that when clicked, requests focus and starts playback? I had a problem once that they played a "tick" sound to provide feedback of a click. They would take audio focus away from my app when that happened. In your XML set this value to false for all your buttons in that activity:

android:soundEffectsEnabled = 'false'

2) Check for the installation of other media player apps that also request focus. Are they requesting focus right after losing it? If so there's not much you can do about this other than warn your users not to install this app.

于 2012-10-04T06:15:28.917 回答