gpt4 book ai didi

ios - 如何知道 AVSpeechUtterance 何时结束,以便继续应用事件?

转载 作者:行者123 更新时间:2023-11-28 09:34:09 25 4
gpt4 key购买 nike

AVSpeechUtterance 正在说话时,我想等到它完成后再做其他事情。

AVSpeechSynthesizer 的一个属性似乎指示语音何时发生:

isSpeaking

尽管这个问题听起来既愚蠢又简单,但我想知道如何使用/检查此属性以等到语音结束后再继续?

或者:

有一个代表,我也不知道如何使用,它有能力在话语结束时做某事:

AVSpeechSynthesizerDelegate

有一个答案,here , 那就是说要用这个。但这对我没有帮助,因为我不知道如何使用委托(delegate)。

更新:

这是我设置口语课的方式:

import AVFoundation

class CanSpeak: NSObject, AVSpeechSynthesizerDelegate {

let voices = AVSpeechSynthesisVoice.speechVoices()
let voiceSynth = AVSpeechSynthesizer()
var voiceToUse: AVSpeechSynthesisVoice?

override init(){
voiceToUse = AVSpeechSynthesisVoice.speechVoices().filter({ $0.name == "Karen" }).first
}

func sayThis(_ phrase: String){
let utterance = AVSpeechUtterance(string: phrase)
utterance.voice = voiceToUse
utterance.rate = 0.5
voiceSynth.speak(utterance)
}
}

更新 2:错误的解决方法...

在 gameScene 中使用上面提到的 isSpeaking 属性:

voice.sayThis(targetsToSay)

let initialPause = SKAction.wait(forDuration: 1.0)
let holdWhileSpeaking = SKAction.run {
while self.voice.voiceSynth.isSpeaking {print("STILL SPEAKING!")}
}
let pauseAfterSpeaking = SKAction.wait(forDuration: 0.5)
let doneSpeaking = SKAction.run {print("TIME TO GET ON WITH IT!!!")}

run(SKAction.sequence(
[ initialPause,
holdWhileSpeaking,
pauseAfterSpeaking,
doneSpeaking
]))

最佳答案

委托(delegate)模式是面向对象编程中最常用的设计模式之一,它并不像看起来那么难。对于您的情况,您可以简单地让您的类(class)(游戏场景)成为 CanSpeak 类(class)的代表。

protocol CanSpeakDelegate {
func speechDidFinish()
}

接下来将 AVSpeechSynthesizerDelegate 设置为您的 CanSpeak 类,声明 CanSpeakDelegate,然后使用 AVSpeechSynthesizerDelegate 委托(delegate)函数。

class CanSpeak: NSObject, AVSpeechSynthesizerDelegate {

let voices = AVSpeechSynthesisVoice.speechVoices()
let voiceSynth = AVSpeechSynthesizer()
var voiceToUse: AVSpeechSynthesisVoice?

var delegate: CanSpeakDelegate!

override init(){
voiceToUse = AVSpeechSynthesisVoice.speechVoices().filter({ $0.name == "Karen" }).first
self.voiceSynth.delegate = self
}

func sayThis(_ phrase: String){
let utterance = AVSpeechUtterance(string: phrase)
utterance.voice = voiceToUse
utterance.rate = 0.5
voiceSynth.speak(utterance)
}

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
self.delegate.speechDidFinish()
}
}

最后,在您的游戏场景类中,只需符合 CanSpeakDelegate 并将其设置为您的 CanSpeak 类的委托(delegate)。

class GameScene: NSObject, CanSpeakDelegate {

let canSpeak = CanSpeak()

override init() {
self.canSpeak.delegate = self
}

// This function will be called every time a speech finishes
func speechDidFinish() {
// Do something
}
}

关于ios - 如何知道 AVSpeechUtterance 何时结束,以便继续应用事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com