2

How do applications like Soundcloud stop another app's MediaPlayer? For example, when I am playing a song through Google Music and I open SoundCloud, the song from Google Music stops playing as soon as the Soundcloud song starts. I might be missing something obvious but I have always wondered how this is achieved.

Thanks, Justin

4

2 回答 2

5

使用音频焦点。请参阅请求音频焦点

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.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
    // Start playback.
}
于 2013-05-03T02:16:14.427 回答
1

添加到@TCA的答案:

只有一个 AudioManager。因此,音频焦点被一一分配给每个请求它的应用程序。这意味着如果另一个应用程序请求音频焦点,您的应用程序将失去它。您将通过您在请求音频焦点时注册的音频焦点更改侦听器( TCA 的答案中的 afChangeListener )的 onAudioFocusChange 处理程序收到音频焦点丢失的通知。

private OnAudioFocusChangeListener focusChangeListener =
      new OnAudioFocusChangeListener() {
              public void onAudioFocusChange(int focusChange) {
                         AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                switch (focusChange) {

                       case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                       //Transient audio loss
                       break;

                       case (AudioManager.AUDIOFOCUS_LOSS) :
                       //Audio focus loss. Stop playback.
                       break;

                       case (AudioManager.AUDIOFOCUS_GAIN) :
                       //Audio focus gain. Start playback.
                       break;
                       default: break;
}
}
};
于 2016-05-22T12:43:12.243 回答