How to stop and resume background audio from iPhone app?

孤街浪徒 提交于 2019-11-27 22:37:53

You cannot do this for all applications. For applications that use the iPod player in their applications:

Assuming your application is in foreground. You can do this:

MPMusicPlayerController *mp = [MPMusicPlayerController iPodMusicPlayer];        
[mp stop]; // or [mp pause]

This needs the MediaPlayer.framework and also #import <MediaPlayer/MediaPlayer.h>.

Read more at MPMusicPlayerController Reference.


For doing it through Audio Player Sessions you can use the property kAudioSessionCategory_SoloAmbientSound. Reference here.

This is similar to AVAudioSessionCategorySoloAmbient defined in AVAudioSession class.

Quoting from the documentation:

When you use this category, audio from other apps is silenced.

Rebecca Duhard

A little late to the party but for those looking for a solution to the problem of pausing and unpausing background (i.e. ipod music) after playing sounds, you should be using the following when deactivating your audio session.

[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

//New method that's not deprecated:

[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

Whenever you do not require the audio session in your application (i.e. when you're not outputting any sound) you should be deactivating it. Where it makes sense, you should use this method so that any background audio is notified and may resume (applications receiving this notification do not necessarily have to resume).

In addition, you must use the appropriate audio category to allow your sound to play exclusively where required. This can be done with any of the categories other than AVAudioSessionCategoryAmbient. This will automatically pause the background audio for you when your Audio session becomes active. It will not, however, reactivate any background audio, that is done by using the above code. In which case, as stated earlier, background audio then decides what to do with the notification.

Side note, another option to look into is audio 'ducking'. If it's not imperative that your sound plays alone, such as a simple alert sound, try using ducking which will lower the volume of background audio to play your sound and when complete will raise the background audio back to normal when you're sound has finished playing. See Configure your Audio Session for more details on these concepts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!