ios - Swift - AVSpeechSynthesizer - 如何运行回调 onError
问题描述
我AVSpeechSynthesizer
习惯用德语发音一些文本。有时它工作得很好,有时它不是出于我不知道的原因(没有错误,因为该speak()
方法没有抛出,我唯一能观察到的是控制台中记录的以下消息):
_BeginSpeaking: couldn't begin playback
我试图在AVSpeechSynthesizerDelegate
发生错误时在其中找到一些 API 来注册回调,但我没有找到。
最接近的匹配是这个(但它似乎只适用于 macOS,而不适用于 iOS):https ://developer.apple.com/documentation/appkit/nsspeechsynthesizerdelegate/1448407-speechsynthesizer?changes=_10
您可以在下面找到我如何在我的应用程序中初始化和使用语音合成器:
class Speaker: NSObject, AVSpeechSynthesizerDelegate {
class func sharedInstance() -> Speaker {
struct Singleton {
static var sharedInstance = Speaker()
}
return Singleton.sharedInstance
}
let audioSession = AVAudioSession.sharedInstance()
let synth = AVSpeechSynthesizer()
override init() {
super.init()
synth.delegate = self
}
func initializeAudioSession() {
do {
try audioSession.setCategory(.playback, mode: .spokenAudio, options: .duckOthers)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
}
}
func speak(text: String, language: String = "de-DE") {
guard !self.synth.isSpeaking else { return }
let utterance = AVSpeechUtterance(string: text)
let voice = AVSpeechSynthesisVoice.speechVoices().filter { $0.language == language }.first!
utterance.voice = voice
self.synth.speak(utterance)
}
}
音频会话初始化在应用程序启动期间运行一次。
之后,通过运行以下代码来合成语音:
Speaker.sharedInstance.speak(text: "Lederhosen")
问题是我无法知道语音合成是否成功——UI 显示“正在说话”状态,但实际上没有说话。
解决方案
推荐阅读
- optaplanner - 从 ShadowVariableListener 中的 ProblemFactCollectionProperty 和 PlanningEntityCollectionProperty 中选择,就像在 ContraintProvider 中一样
- javascript - 如何提取文本框的值(V-Model)?
- google-schemas - Google 电子邮件标记中缺少突出显示
- python - python scrapy蜘蛛爬取不同url的所有子站点
- java - Java Jackson反序列化实现接口的抽象类子
- shell - variable=$(...) 是否将命令或命令的结果存储在 POSIX sh 中
- r - 如何嵌套小标题
- java - Eclipse动态web项目的Tomcat安装配置
- mysql - MySQL 8 st_distance_sphere 为不同的 SRID 提供不同的值
- r - 计算条件为 2.0 的观测值之和