I am trying to pronounce sentences with time intervals, but the problem is that after the synthesizer pronounces it for the first time, loop runs through straight away till the end. The utterance works well, but there are no pauses between.
How can I do that loop switches to next item only after the speech synthesizing task is finished?
EDIT: Maybe, it's possible that loop waits for didFinish
each time, and then didFinish
tells loop when it can continue?
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")
}
}