快速文本到语音

Sar*_*lik 11 text-to-speech swift

我有一段代码无法正常工作,但也没有给我一个运行时错误.演讲者没有发言.

let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: audioTextField.text)
myUtterance.rate = 0.3
synth.speak(myUtterance)
Run Code Online (Sandbox Code Playgroud)

有没有我错过的代码或者其他什么?非常感谢帮助.

编辑:它不适用于任何@IBActions,但在视图中正常工作加载功能....

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*agó 32

此代码正常工作(来自Apple文档)

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

let synth = AVSpeechSynthesizer()
synth.speak(utterance)
Run Code Online (Sandbox Code Playgroud)

记得导入AVFoundation

import AVFoundation
Run Code Online (Sandbox Code Playgroud)

  • 您需要将合成器定义为全局变量。如果是局部变量,则在 iOS16 上不起作用。将给出“无法列出语音文件夹”错误。 (6认同)