【发布时间】:2021-02-10 22:52:31
【问题描述】:
我正在尝试用时间间隔来发音句子,但问题是在合成器第一次发音后,循环会一直运行到最后。话语效果很好,但中间没有停顿。
只有在语音合成任务完成后,才能让循环切换到下一个项目?
编辑:也许,循环可能每次都等待didFinish,然后didFinish 告诉循环何时可以继续?
let speaker = Speaker()
let capitals = ["Canberra is the capital of Australia", "Seoul is the capital of South Korea", "Tokyo is the capital of Japan", "Berlin is the capital of Germany"]
var body: some View {
Button("Play Sound") {
playSound()
}
}
func playSound() {
for item in 0..<capitals.count {
let timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in
speaker.speak("\(capitals[item])")
print("I am out")
}
}
}
...
import AVFoundation
class Speaker: NSObject {
let synth = AVSpeechSynthesizer()
override init() {
super.init()
synth.delegate = self
}
func speak(_ string: String) {
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
utterance.rate = 0.5
synth.speak(utterance)
}
}
extension Speaker: AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
print("all done")
}
}
【问题讨论】:
-
你研究过信号量吗?
-
不知道信号量。看起来非常非常有趣!!!这对我来说是一个发现。我去找找。
-
另一种方法是使用带有完成处理程序的递归函数,从您的
didFinish函数调用。 -
我希望以递归方式更好地控制暂停,因为我理解它总是相同的暂停时间。而且我不能每次都做不同的停顿(可以吗?)
标签: swift avfoundation