How do you run AVSpeechSynthesizer from command-line Swift on MacOS?

This code doesn't work. What should I do when it stops prematurely?

Code Block swift
import Foundation
import AVFoundation
print("Hello, World!")
var synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "Hello World!")
utterance.voice = AVSpeechSynthesisVoice(identifier: "com.apple.speech.synthesis.voice.samantha.premium")
utterance.rate = 0.5
synthesizer.speak(utterance)
print("Done.")


You need to keep your process alive until the speech is finished.

Please try something like this:
Code Block
import Foundation
import AVFoundation
class MyAVSpeechSynthesizerDelegate: NSObject, AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
print("Done.")
exit(0)
}
}
print("Hello, World!")
var synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "Hello World!")
utterance.voice = AVSpeechSynthesisVoice(identifier: "com.apple.speech.synthesis.voice.samantha.premium")
utterance.rate = 0.5
let myDelegate = MyAVSpeechSynthesizerDelegate()
synthesizer.delegate = myDelegate
synthesizer.speak(utterance)
RunLoop.main.run()


How do you run AVSpeechSynthesizer from command-line Swift on MacOS?
 
 
Q