2
votes

I am trying to play an audio through earpiece speaker and it is working fine. The same code is not working in following situation.

  1. open camera to record a video
  2. Instead of start recording, cancel it
  3. 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];
}
2
Does this answer your question? How to play audio through built-in earpiece speakershim

2 Answers

4
votes

Change audio route for 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];
}
4
votes

Here is the solution to make AVAudioSession route to Ear Speaker (Built in Speaker) or in bottom Speaker for Swift 4.2, iOS 12, SDK 11:

1) Create a file in your project called AudioSession and implement these 3 functions.

import AVFoundation
import UIKit

let audioSession = AVAudioSession.sharedInstance()

func configureAudioSessionCategory() {
  print("Configuring audio session")
  do {
    try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.voiceChat)
    try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
    print("AVAudio Session out options: ", audioSession.currentRoute)
    print("Successfully configured audio session.")
  } catch (let error) {
    print("Error while configuring audio session: \(error)")
  }
}

func configureAudioSessionToSpeaker(){
    do {
        try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
        try audioSession.setActive(true)
        print("Successfully configured audio session (SPEAKER-Bottom).", "\nCurrent audio route: ",audioSession.currentRoute.outputs)
    } catch let error as NSError {
        print("#configureAudioSessionToSpeaker Error \(error.localizedDescription)")
    }
}

func configureAudioSessionToEarSpeaker(){

    let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    do { ///Audio Session: Set on Speaker
        try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
        try audioSession.setActive(true)

        print("Successfully configured audio session (EAR-Speaker).", "\nCurrent audio route: ",audioSession.currentRoute.outputs)
    }
    catch{
        print("#configureAudioSessionToEarSpeaker Error \(error.localizedDescription)")
    }
}

2) In your current viewcontroller viewWillAppear that you play audio, call:

    configureAudioSessionCategory()

3) If you want to put audio on speaker, call function:

    configureAudioSessionToSpeaker()

If you want to put audio on mic, call function:

    configureAudioSessionToEarSpeaker()

*I will make some tags because its new for swift 4.2 and its hard (or nothing) to find on google or here while you search for this topic.

Tags: avaudio session to ear speaker, audio route to top speaker, earpiece speaker, deafult speaker, bottom speaker, loud speaker.