Setting the AVAudioSession category in AppDelegate.m

一曲冷凌霜 提交于 2019-12-13 04:41:55

问题


So I hate to have to ask this question but I've spent a fair bit of time searching through Apple's documentation and Google with no avail. I'm simply trying to set the AVAudioSession category for my app ONCE, when the applicationDidFinishLaunching. I have an app that plays an audio stream and I would like it to continue playing when the app enters the background, so I'm trying to use the Playback category. Here is my code for AppDelegate.m :

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];

// create window and set up navigation controller
[window addSubview:myNavController.view];
[window makeKeyAndVisible];

}

# pragma mark -
# pragma mark AVAudioSession Delegate Methods 
- (void)beginInterruption {
}
- (void)endInterruption {
}
- (void)endInterruptionWithFlags:(NSUInteger)flags {
}
- (void)inputIsAvailableChanged:(BOOL)isInputAvailable {
}

With this code, the audio fades out anytime I hit the home button, putting the app in the background. Any help is much appreciated, I hope that it is a quick fix type of answer for anybody who has done this before.


回答1:


First add the UIBackgroundModes key to your Info.plist file if you haven't done already. More info here.

If you have done that already, which framework do you use to play your media?




回答2:


Thanks for the help Irene. You are pretty much right with your answer except I just wanted to provide the steps that were necessary for it to work for me. I read the apple documentation that you posted and for some reason it left these important details out:

  1. When you add the UIBackgroundModes key in the .plist file, you have to make it an array.
  2. The value for Item 0 of the array should be audio.

Of course your app should also take care of setting its audio session category in combination with setting this key.



来源:https://stackoverflow.com/questions/4620376/setting-the-avaudiosession-category-in-appdelegate-m

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