AVAudioSession: play sound through speaker speaker

I am trying to play sound through the speaker of the speaker, and it works fine. The same code does not work in the following situation.

  • open camera to record video
  • Cancel recording instead of starting
  • Then, trying to play sound through the speaker, it does not work. It plays the main speaker

Here is my code for playing sound through the 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 the code, and the user clicks cancel,

 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { NSLog(@"here"); [self dismissViewControllerAnimated:YES completion:nil]; } 
+1
ios objective-c audio avaudiosession
source share
1 answer

Change the sound route for the cancel button, solve the problem.

 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { NSError *error = nil; AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayback error:&error]; [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil]; [session setActive: YES error:nil]; videoPicker = nil; [self dismissViewControllerAnimated:YES completion:nil]; } 
+2
source share

All Articles