Swift text to speech

Saransh Malik picture Saransh Malik · Feb 3, 2017 · Viewed 12k times · Source

I have a block of code that is not working, but not giving me a runtime error either. There is just no speech coming out of the speaker.

let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: audioTextField.text)
myUtterance.rate = 0.3
synth.speak(myUtterance)

Is there any code I'm missing out on or is it something else? Help would be much appreciated.

Edit: It's not working in any @IBActions, but is working fine in the view did load function....

override func viewDidLoad() {
    super.viewDidLoad()
    speechRecognizer?.delegate = self
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
    tick()
    requestSpeechAuth()
//WORKS HERE
}

@IBAction func audioButtonPressed(_ sender: Any) {
//DOESN"T WORK HERE    
    if isRecording {
        stopRecording()
    } else {
        startRecording()
    }
}

Answer

Alex Tarragó picture Alex Tarragó · Feb 3, 2017

This code is working (from Apple docs)

let string = "Hello, World!"
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")

let synth = AVSpeechSynthesizer()
synth.speak(utterance)

Remember to import AVFoundation

import AVFoundation