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

标签 macos swift text-to-speech command-line-tool

我正在为 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/

相关文章:

android - TextToSpeech android 构建版本不播放音频

macos - 操作系统 : Remap caps lock key to funktion key or Fn?

java - 是否可以从其他操作系统针对 Windows Azure 进行开发?

ios - 如何正确组合 CGAffineTransform 矩阵?

ios - 为什么我不能将 UICollectionViewFlowLayout 中的 referenceSizeForFooterInSection 与 EstimateItemSize 一起使用?

Azure 文本转语音 API - 仅限 10 分钟的音频?

android - 如何让android设备 "speak"中文?

c - 如何在 OS X/C 中获取文件的最后修改时间?

ios - UIApplicationDelegate 与 NSApplicationDelegate,MainMenu.xib

ios - 使用 Decodable 解码同一键中的不同对象数组