I am adding text to speech features in my iOS app using the code below:
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
try! AVAudioSession.sharedInstance().setActive(true)
try! AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
let speech : String = "You have the following items in your To-do list: "
let speechUtterance : AVSpeechUtterance = AVSpeechUtterance(string: speech)
AVSpeechSynthesizer().speakUtterance(speechUtterance)
The code is working perfectly fine, but the sound is coming from the phone's microphones. I want to use the speakers rather than the microphone. How do I achieve this ?
I used SFSpeechRecognizer for speech recognition and after that in order to play utterance to speaker you must do following.
  let audioSession = AVAudioSession.sharedInstance()  
     do {
    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try audioSession.setMode(AVAudioSessionModeSpokenAudio)
    try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
                    let currentRoute = AVAudioSession.sharedInstance().currentRoute
                        for description in currentRoute.outputs {
                            if description.portType == AVAudioSessionPortHeadphones {
                                 try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.none)
                                print("headphone plugged in")
                            } else {
                                print("headphone pulled out")
                                 try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
                            }
                    }
} catch {
      print("audioSession properties weren't set because of an error.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With