这是我的游乐场代码:
import AVFoundation var 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 UIKit import AVFoundation class 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() } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。