当添加新字符串时,Avspechsynthesizer不起作用[Swift 4]



im使用以下代码在随机时间读取随机句子。但是,当avspechsynthesizer仍在说上一个句子时,我遇到了问题,当时句子被读取了,这使第二个句子不说。我要问的是,在说完第一句话后,我该如何说出第二句话?

任何进口都将不胜感激。欢呼

我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {
var myTimer = Timer()
   let string = ["what kind of car do you have?", "do you like the beach?","did you bring a towel?","There are big waves today"]
var randomTimer = Int()

@objc func speakToMe(){
    let random = Int.random(in: 0...3)
    randomTimer = Int.random(in: 0...2)
    print(randomTimer)
    print(string[random])

let utterance = AVSpeechUtterance(string: string[random])
utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
utterance.rate = 0.1
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
override func viewDidLoad() {
    super.viewDidLoad()
    speakToMe()
    myTimer = Timer.scheduledTimer(timeInterval: TimeInterval(randomTimer), target: self, selector: #selector(ViewController.speakToMe), userInfo: nil, repeats: true)
}

}   

您可以简单地使用AVSpeechSynthesizerDelegate,然后可以从代码中删除计时器。

和使用AVSpeechSynthesizerDelegate首先,您需要使用AVSpeechSynthesizerDelegate确认视图控制器,如下所示:

class ViewController: UIViewController, AVSpeechSynthesizerDelegate {

接下来是您需要添加

synthesizer.delegate = self

在您的viewDidLoad方法中。而且您需要声明

let synthesizer = AVSpeechSynthesizer()

在方法之外和班级内部。

您可以使用randomElement属性从string数组中查找随机元素。

,您的最终代码看起来像:

import UIKit
import AVFoundation
class ViewController: UIViewController, AVSpeechSynthesizerDelegate {
    let string = ["what kind of car do you have?", "do you like the beach?","did you bring a towel?","There are big waves today"]
    let synthesizer = AVSpeechSynthesizer()
    override func viewDidLoad() {
        super.viewDidLoad()
        synthesizer.delegate = self
        speakToMe()
    }
    @objc func speakToMe(){
        let utterance = AVSpeechUtterance(string: string.randomElement()!)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
        utterance.rate = 0.1
        synthesizer.speak(utterance)
    }
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        speakToMe()
    }
}

编辑:

,由于您在数组中仅使用4个元素,因此在随机字符串进行随机字符串时,有可能重复同一句子,因此您可以在此处添加一种逻辑,以阻止它。

更新您的speakToMe功能如下:

@objc func speakToMe(){
    var randomStr = string.randomElement()!
    while previousStr == randomStr {
        randomStr = string.randomElement()!
    }
    previousStr = randomStr
    let utterance = AVSpeechUtterance(string: randomStr)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
    utterance.rate = 0.1
    synthesizer.speak(utterance)
}

和声明var previousStr = ""功能外部。

相关内容

  • 没有找到相关文章

最新更新