我正在为 Mac OS X 编写莫尔斯电码命令行工具,使用 Swift 作为脚本语言编写。我想让用户可以选择使用 Apple 的 NSSpeechSynthesizer 收听摩尔斯电码。我可以毫不费力地让它在应用程序中运行。但是在命令行工具或 Swift 脚本中,startSpeakingString() 函数是听不见的——除非我逐行执行代码。
这是 Swift 中的代码(对于适当的命令行工具或脚本来说是相同的)
import Foundation
import AppKit
var synth:NSSpeechSynthesizer = NSSpeechSynthesizer.init()
synth.startSpeakingString("dit dah")
这是 Objective-C 命令行工具中的代码
@import Foundation;
@import AppKit;
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSSpeechSynthesizer *synth = [[NSSpeechSynthesizer alloc] init];
[synth startSpeakingString:@"dit dah"];
}
return 0
}
NSSpeechSythesizer 实例似乎在所有情况下都是合法的。 startSpeakingString() 函数在所有情况下都返回 true。这是我的 repo 协议(protocol)(进行中的工作):https://github.com/jpavley/swift-scripts
最佳答案
NSSpeechSynthesizer.isAnyApplicationSpeaking() 等待语音结束。
import Foundation
import AppKit
class Speaker: NSObject , NSSpeechSynthesizerDelegate {
var synth : NSSpeechSynthesizer!
func run() {
self.synth = NSSpeechSynthesizer.init()
self.synth.delegate = self
self.synth.startSpeakingString("First word")
while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {}
}
}
var speak : Speaker = Speaker.init()
speak.run()
关于macos - Swift 或 Objective-C 命令行工具和文本到语音不输出音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29732244/