IOS: Play sound while app in background

匆匆过客 提交于 2019-12-03 14:30:01

In addition to having background mode audio in your Info.plist you need to set the shared audio session to the correct mode for your app and activate it just before playing your sound in the background:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
NSLog(@"Activating audio session");
if (![audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&error]) {
    NSLog(@"Unable to set audio session category: %@", error);
}
BOOL result = [audioSession setActive:YES error:&error];
if (!result) {
    NSLog(@"Error activating audio session: %@", error);
}
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Don't forget to deactivate the audio session when you are done playing sounds:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
NSLog(@"Deactivating audio session");
BOOL result = [audioSession setActive:NO error:&error];
if (!result) {
    NSLog(@"Error deactivating audio session: %@", error);
}

Before starting playing a sound in the background, set up a background task. It seems that iOS refuses to start a sound in the background if the remaining background time is less than 10 seconds.

Avtar Guleria

On iOS only some of the applications are allowed to run in background. One of them is Audio player application but for them you need to set "required background modes" with "audio" (App can play audio) in your Info.plist.

And Yes if you are able to get Location in Background then you must have set this key in your Plist. Add also audio permission in the plist.

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