Saransh Malik
Saransh Malik

Reputation: 746

Swift text to speech

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()
    }
}

Upvotes: 24

Views: 21026

Answers (1)

Alex Tarragó
Alex Tarragó

Reputation: 966

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

Upvotes: 54

Related Questions