在 macOS Mojave 上,在 cocoa 应用程序中,如何使用 AVSpeechSynthesizer?

On macOS Mojave, in a cocoa application, how to use AVSpeechSynthesizer?

AVSpeechSynthesizer is marked as available on macOS Mojave beta.

以前它仅适用于 iOS、tvOS 和 watchOS。但是如果我在 Xcode 10 中准备一个小的 macOS 测试项目,它会给我一个错误 "Use of unresolved identifier 'AVSpeechSynthesizer'"。在顶部,我有:

import Cocoa
import NaturalLanguage
import AVFoundation

我的代码是:

let string = "Mickey mouse went to town"

let recognizer = NLLanguageRecognizer()
recognizer.processString(string)
let language = recognizer.dominantLanguage!.rawValue

let speechSynthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: language)
speechSynthesizer.speak(utterance)

它与 iOS 上的代码完全相同,但在 iOS 上它有效,在 macOS 上它给出错误。任何帮助深表感谢。谢谢

目前 AVFAudio.h 在 Mojave 上有这个:

#if TARGET_OS_IPHONE
#import <AVFAudio/AVAudioSession.h>
#import <AVFAudio/AVSpeechSynthesis.h>
#endif

并且AVSpeechSynthesizer和朋友在AVSpeechSynthesis.h中声明。这是您看到该错误的技术原因,这些 header 仅在为 iOS.

编译时包含在内

但我已尝试手动导入 header,但我认为 AVSpeechSynthesizer 在 Mojave 上无法正常工作,即使 #if 不存在也是如此。尝试在 Mojave 上创建 AVSpeechUtterance 总是 returns nil。

因此,这要么是 Mojave 上未完成的工作,要么 header 注释不正确,无法通过 Mojave 上的 AVFoundation 进行语音合成。请注意,NSSpeechSynthesizer 仍然存在并且未被标记为已弃用。