Thursday, June 6, 2013

AVAudioSession setActive example in Objective C (iOS).

AVAudioSession setActive

Activates or deactivates your app’s audio session.

- (BOOL)setActive:(BOOL)beActive error:(NSError **)outError

Use YES to activate your app’s audio session or NO to deactivate it.
On input, specify a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value of [AVAudioSession setActive]
Returns YES on success or NO on failure.

Discussion of [AVAudioSession setActive]
If another app’s active audio session has higher priority than your app, and that other audio session does not allow mixing with other apps, attempting to activate your audio session may fail.

AVAudioSession setActive example.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
NSError * audio_session_err = nil;
[audio_session setCategory: AVAudioSessionCategoryPlayAndRecord error:&audio_session_err];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&audio_session_err];
[[AVAudioSession sharedInstance] setDelegate:self];

UInt32 audioRouteOverride = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,sizeof (audioRouteOverride),&audioRouteOverride);
UInt32 allowMixing = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixing), &allowMixing);   

if (audio_session_err) {
  NSLog(@"audioSession: %@ %d %@", [audio_session_err domain], [audio_session_err code], [audio_session_err description]);
} else {
  audio_session_err = nil;
  [[AVAudioSession sharedInstance] setActive:YES error:&audio_session_err];
  if (!audio_session_err) NSLog(@"audio session is activated successfully");

Example of [AVAudioSession setActive].
in my appDelegate i have:

NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
before a song is going to be played a set:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
i notify my application on "playerItemDidPlayToEnd", stop the player and tell other apps like the to become active again

_avPlayer = nil;
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:&sessionError];

AVAudioSession setActive example.
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &fooError];
//Activate the session
[audioSession setActive:YES error: &fooError];

End of AVAudioSession setActive example article.