Thursday, June 6, 2013

AVAudioSession AVAudioSessionCategoryAmbient example in Objective C (iOS).


AVAudioSession AVAudioSessionCategoryAmbient

NSString *const AVAudioSessionCategoryAmbient;

For an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.
This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays over iPod audio. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).
AVAudioSession AVAudioSessionCategoryAmbient example.
You have to do the following when the user chooses to remove audio:

[player stop];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

Example of [AVAudioSession AVAudioSessionCategoryAmbient].
By default, sounds played interrupt iPod, as you have seen. In order to tell the system that you want the sounds you're playing to be mixed in with other sounds on the system, such as iPod, you need to set the category of your AVAudioSession to AVAudioSessionCategoryAmbient, like this:

[AVAudioSession sharedInstance].category = AVAudioSessionCategoryAmbient;
Do this before you begin playing sounds, and you should get the desired effect.

AVAudioSession AVAudioSessionCategoryAmbient example.
 In iOS 6.0, apple provide a new function call setCategory:withOptions:. It work. So the code is just like this:

    AVAudioSession *session =[AVAudioSession sharedInstance];
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version <6.0) {
        [session setCategory:AVAudioSessionCategoryAmbient error:nil];
    }
    else {
        [session setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil];
    }

End of AVAudioSession AVAudioSessionCategoryAmbient example article.