AVSpeechSynthesizer 在添加要朗读的新字符串时不工作 [xcode - swift 4]

AVSpeechSynthesizer not working when new strings are added to be spoken [xcode - swift 4]

我使用下面的代码随机阅读随机句子。 然而,当 AVSpeechSynthesizer 仍在说前一个句子时调用随机句子进行阅读时,我 运行 遇到了这个问题,使得第二个句子没有被说出来。我想问的是,第一句说完了,怎么才能让第二句说完呢??

任何进口将不胜感激。 干杯

这是我的代码:

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()

在方法之外,在 class 之内。

并且您可以使用 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 = ""