Thursday, June 6, 2013

AVAudioSession setActive error example in Objective C (iOS).


AVAudioSession setActive error

Activates or deactivates your app’s audio session.

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

Parameters of [AVAudioSession setActive error]
beActive
Use YES to activate your app’s audio session or NO to deactivate it.
outError
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
Returns YES on success or NO on failure.

Discussion of [AVAudioSession setActive error]
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 error 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];
NSLog(@"!");

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 error].
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 music.app to become active again

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

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

End of AVAudioSession setActive error example article.