Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the iPhone speakers with AVSpeechSynthesizer

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 ?

like image 294
Ashish Agarwal Avatar asked Apr 05 '16 09:04

Ashish Agarwal


1 Answers

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.")
}
like image 186
Ivan Skrobot Avatar answered Nov 18 '22 06:11

Ivan Skrobot