ios – 如何在Swift中的while循环的每次迭代中立即发生语音?

ios – 如何在Swift中的while循环的每次迭代中立即发生语音?,第1张

概述这是我的游乐场代码: import AVFoundationvar speechsynth: AVSpeechSynthesizer = AVSpeechSynthesizer()let wordsToSpeak = ["word one","word two","word three","word four"]let endTime = NSDate().dateByAddingTi 这是我的游乐场代码:
import AVFoundationvar speechsynth: AVSpeechSynthesizer = AVSpeechSynthesizer()let wordsToSpeak = ["word one","word two","word three","word four"]let endTime = NSDate().dateByAddingTimeInterval(10)while endTime.timeIntervalSinceNow > 0 {     //workaround for iOS8 BUG    var beforeSpeechString : String = " "    var beforeSpeech:AVSpeechUtterance = AVSpeechUtterance(string: beforeSpeechString)    speechsynth.speakUtterance(beforeSpeech)    //realstring to speak    var speechString: String = wordsToSpeak[0]    var nextSpeech:AVSpeechUtterance = AVSpeechUtterance(string: speechString)    nextSpeech.voice = AVSpeechSynthesisVoice(language: "en-US")    nextSpeech.rate = AVSpeechUtteranceMinimumSpeechRate    speechsynth.speakUtterance(nextSpeech)}

目前,讲话在while循环完成后开始.

如何在每次迭代过程中说出并完成说话,然后再进行循环的下一次迭代?

解决方法 将每个单词视为任务,在Delegate的dIDFinishSpeechUtterance方法中触发下一个任务.
import UIKitimport AVFoundationclass VIEwController: UIVIEwController,AVSpeechSynthesizerDelegate {    var queue: dispatch_queue_t = dispatch_queue_create(        "com.test.whatever.queue",disPATCH_QUEUE_SERIAL)    var index: Int = 0    let words: [String] = ["word one","word four"]    var speechsynth: AVSpeechSynthesizer = AVSpeechSynthesizer()    overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        // Do any additional setup after loading the vIEw,typically from a nib.        speechsynth.delegate = self        self.speechCurrentWord()    }    func speechCurrentWord(){        dispatch_async(queue,{ () -> VoID in            var beforeSpeechString : String = " "            var beforeSpeech:AVSpeechUtterance = AVSpeechUtterance(string: beforeSpeechString)            self.speechsynth.speakUtterance(beforeSpeech)            var nextSpeech:AVSpeechUtterance = AVSpeechUtterance(string: self.words[self.index])            nextSpeech.voice = AVSpeechSynthesisVoice(language: "en-US")            nextSpeech.rate = AVSpeechUtteranceMinimumSpeechRate            self.speechsynth.speakUtterance(nextSpeech)        })    }    func speechSynthesizer(synthesizer: AVSpeechSynthesizer!,dIDFinishSpeechUtterance utterance: AVSpeechUtterance!) {        index++        if index < self.words.count {            self.speechCurrentWord()        }    }}
总结

以上是内存溢出为你收集整理的ios – 如何在Swift中的while循环的每次迭代中立即发生语音?全部内容,希望文章能够帮你解决ios – 如何在Swift中的while循环的每次迭代中立即发生语音?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1114288.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存