在音乐应用和非音乐应用之间切换?

时间:2015-03-19 06:29:32

标签: android audio android-audiomanager audio-player android-music-player

我正在开发音乐应用程序。我的问题是,当我从我的应用程序播放音乐时,其他音乐播放器的歌曲暂停,但当我播放其他音乐播放器歌曲时播放我的播放器歌曲时,两个播放器歌曲都是混合的。我的音乐播放器歌曲不会暂停(应该暂停)。我使用了以下代码。请帮帮....

public void playAudio() {
    OnAudioFocus onAudioFocus=new OnAudioFocus(this);

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.requestAudioFocus(onAudioFocus, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    MusicPlayerActivity.mediaPlayer.start();
}

class OnAudioFocus implements AudioManager.OnAudioFocusChangeListener {

    HomeActivity onAudioFocus;

    public OnAudioFocus(HomeActivity onAudioFocus) {
        this.onAudioFocus = onAudioFocus;
    }

    public void onAudioFocusChange(int focusChange) {

        switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            MusicPlayerActivity.mediaPlayer.start();


            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            if (MusicPlayerActivity.mediaPlayer.isPlaying())
                 onAudioFocus.stopAudio();

                break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            if (MusicPlayerActivity.mediaPlayer.isPlaying())
                 onAudioFocus.pauseAudio();

                break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            if (MusicPlayerActivity.mediaPlayer.isPlaying())
                 MusicPlayerActivity.mediaPlayer.setVolume(0.1f, 0.1f);
                break;

        }
    }
}

0 个答案:

没有答案