AVAudioPlayer doesn't start playing in background

房东的猫 提交于 2019-12-01 14:24:40

Your app cannot start playing audio in the background. And this makes sense. Think what the device would be like if an app that the user is not actively using could suddenly start producing sound! Remember, to the user, sending an app to the background is the naive equivalent of quitting that app. Your app must not rise like a zombie from the dead and start making noise!

The background audio setting allows your app that was producing audio while in the foreground to continue to do so when it then goes into the the background. It then can continue being in charge of the audio (if it receives remote events) until some other app produces sound; after that, your app is once again out of the running until it is brought to the foreground and produces sound.

So you'll need to start playing some sound before your app goes into the background, if you want this to work.

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

/* And in info.Plist file Required background modes : App PLAYS Audio */

iEinstein

Please use this code in - (void)applicationDidEnterBackground:(UIApplication *)application

UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
[app endBackgroundTask:bgTask]; 
}];
AudioSessionSetActive(false);

and use this code in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory);
AudioSessionSetActive(true);

hope this helps.

Faced this very problem. Let me suggest you to use AVAudioSessionCategoryOptionMixWithOthers with -setCategory:withOptions:error:. Also, probably it makes sense to activate the session after you set the category, not before.

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