Thursday, June 6, 2013

AVAudioSession AVAudioSessionCategoryPlayback example in Objective C (iOS).


AVAudioSession AVAudioSessionCategoryPlayback

NSString *const AVAudioSessionCategoryPlayback;

For playing recorded music or other sounds that are central to the successful use of your app.
When using this category, your app audio continues with the Silent switch set to silent or when the screen locks. (The switch is called the Ring/Silent switch on iPhone.) To continue playing audio when your app transitions to the background (for example, when the screen locks), you need to add the audio value to the “UIBackgroundModes” in Information Property List Key Reference key in your information property list file.
This category normally prevents audio from other apps from mixing with your app's audio. To allow mixing for this category, use the kAudioSessionProperty_OverrideCategoryMixWithOthers property.

AVAudioSession AVAudioSessionCategoryPlayback example.
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
}

Example of [AVAudioSession AVAudioSessionCategoryPlayback].
if (backgroundSwitch.on) {
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
}else {
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:NULL];
}

AVAudioSession AVAudioSessionCategoryPlayback example.
I have successfully made audio run in the background by adding the following to my applicationDidFinishLaunching

// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];   
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

End of AVAudioSession AVAudioSessionCategoryPlayback example article.