开发者

Interrupting MediaPlayer

开发者 https://www.devze.com 2023-03-13 11:45 出处:网络
My application makes a short announcement once in a while, either via TextToSpeech or using the MediaPlayer. If there is some other music running in the background probably by 开发者_如何转开发some ap

My application makes a short announcement once in a while, either via TextToSpeech or using the MediaPlayer. If there is some other music running in the background probably by 开发者_如何转开发some application using the MediaPlayer, I would like to interrupt this music for a moment and after my announcement resume playing the "background music".

Is there a way to do it?


If you can target API level 8 and above (Android 2.2), then have a look into the AudioManager, specifically requestAudioFocus() with AUDIOFOCUS_GAIN_TRANSIENT and AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK, and abandonAudioFocus().

These give hints to the currently-playing music stream that your app would like to play a brief sound. If you use AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK with requestAudioFocus() you can get a nice effect where the already-playing music pauses, your sound plays, and then the playing music fades back in again when you call abandonAudioFocus().

This works nicely with the built-in media players on the 2.2 devices I've tried it with (Samsung Galaxy S Wi-Fi and HTC Wildfire.) I've not tried it extensively with other music-playing apps, but it definitely works with Spotify, at least, and is the official way of doing exactly what you want to do.

Note that you'll need to work out for yourself when to call abandonAudioFocus() as most sounds are played asynchronously. Luckily, both MediaPlayer and TextToSpeech provide callback mechanisms so they can give you a prod when they've finished playing your sound (this isn't true of SoundPool, so that's more annoying to use audio focus with.)


I don't think there is a standard way to do it for every music player out there. At least for the Android music player you could do:

Intent i;
i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
context.sendBroadcast(i);

Another way to do it would be to set the stream volume for type "music" to 0, and play your announcement on another stream type.

0

精彩评论

暂无评论...
验证码 换一张
取 消