Swift 或 Objective-C 命令行工具和文本到语音不输出音频

Swift or Objective-C command line tool and text to speech not outputting audio

我正在为 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() 函数 returns 在所有情况下都为真。这是我的回购协议(进行中的工作):https://github.com/jpavley/swift-scripts

感谢您的评论,我发现我需要一个 运行 循环。我在 GitHub pannous/caffe-speech-recognition 上找到了灵感,并通过代码重写如下:

import Foundation
import AppKit

println("Hello, World!")

//var synth:NSSpeechSynthesizer = NSSpeechSynthesizer.init()
//var result = synth.startSpeakingString("dit doh")
//println(result)

@objc class SynthDelegate : NSObject, NSSpeechSynthesizerDelegate {

    func run() {
        var synth = NSSpeechSynthesizer.init()
        synth.delegate = self
        synth.startSpeakingString("dit doh")
    }
}

SynthDelegate().run()
sleep(2);

我觉得 sleep(2) 函数调用有点乱(而且不是很好)。我需要研究如何做得更好。

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()