I am trying to play an audio through earpiece speaker and it is working fine. The same code is not working in following situation.
- open camera to record a video
- Instead of start recording, cancel it
- Then, trying to play an audio through earpiece not working. It is playing through main speaker
Here is my code to play audio through earpiece.
-(void)initialAVaudioPlayer
{
if (player==nil) {
NSError *error = nil;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
[session setActive: YES error:nil];
AVAudioSessionPortDescription *routePort = session.currentRoute.outputs.firstObject;
NSString *portType = routePort.portType;
if ([portType isEqualToString:@"Receiver"]) {
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
} else {
[session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
}
NSString *path;
NSError *err;
NSString *name;
name = @"referenceaudio";
path = [[NSBundle mainBundle] pathForResource:name ofType:@"wav"];
if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&err];
if (!err) {
player.numberOfLoops = -1;
}
else{
//NSLog(@"%@",[err description]);
}
}
}
}
Here is code, while user press cancel ,
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
NSLog(@"here");
[self dismissViewControllerAnimated:YES completion:nil];
}