Swift中没有AVSpeechUtterance且没有语音/语音丢失

时间:2018-07-02 16:52:49

标签: ios swift xcode avspeechsynthesizer avspeechutterance

我目前正在使用XCode 9.4.1和Swift组装我的第一个应用程序。在我的代码中,我正在遍历列表,我希望大声说出列表中的每个值。下面是我的代码

// classificationResults is my list
for returnedValue in self.classificationResults{
                    let utterance = AVSpeechUtterance(string: returnedValue)
                    utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
                    utterance.rate = 0.5

                    let synthesizer = AVSpeechSynthesizer()
                    synthesizer.speak(utterance)
                    // print(returnedValue)

在模拟器中运行它时,它可以工作,但是只说允许列表中的前一个或两个值(有7个)。当我直接在我的设备上运行此程序时,没有任何声音。

有什么想法/建议吗?预先感谢

2 个答案:

答案 0 :(得分:0)

我已实现以下代码,以使用AVSpeechSynthesizer将所有文本转换为语音。以此代码为例,您可以尝试使用自己的代码。

class TextToVoiceVC: UIViewController, AVSpeechSynthesizerDelegate {

    var arrSpeechCount = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
    var count : Int = 0
    let speechSynthesizer   = AVSpeechSynthesizer()        

    //----------------------------------------------------------------
    // MARK:- AVSpeechSynthesixerDelegate
    //----------------------------------------------------------------

    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {

    }

    //----------------------------------------------------------------

    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {

        speechSynthesizer.stopSpeaking(at: .word)

        count += 1
        if count < arrSpeechCount.count {
            let speechUtterance = AVSpeechUtterance(string: (arrSpeechCount[count]))
            DispatchQueue.main.async {
                self.speechSynthesizer.speak(speechUtterance)
            }
        }
    }


    //----------------------------------------------------------------
    // MARK:- View Life Cycle Methods
    //----------------------------------------------------------------

    override func viewDidLoad() {
        super.viewDidLoad()
        speechSynthesizer.delegate = self
    }

    //----------------------------------------------------------------

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // Code to start speech
        if speechSynthesizer.isSpeaking {
            speechSynthesizer.stopSpeaking(at: .immediate)
        } else {
            let speechUtterance = AVSpeechUtterance(string: (arrSpeechCount[count]))

            DispatchQueue.main.async {
                self.speechSynthesizer.speak(speechUtterance)
            }
        }
    }
}

此代码在我的模拟器和设备中均有效。希望这对您也有帮助。您应该尝试委托您的数据。

答案 1 :(得分:0)

问题可能出在您的玩家生命周期上:要记住的最重要的事情是保留您的AVSpeechSynthesizer实例,直到发表完整的演讲

将合成器的创建移动到循环之外,并保持活跃直到演讲结束:这个answer可能也有帮助。