AVSpeechSynthesiser窃听ViewDidLoad函数

时间:2018-05-16 07:55:31

标签: swift xcode avfoundation avspeechsynthesizer avspeechutterance

每当我导航到这个视图控制器时,由于某种原因,speakText()中的viewDidLoad函数不起作用,视图控制器需要很长时间才能加载(当我删除时不是这种情况)那条线)。在该行上方,文本标签的文本被设置为要说出的字符串,并且工作正常。每次调用recordTapped时,语音合成都能完美运行。但是,它似乎在viewDidLoad中不起作用。

UPDATE 在分配了语音合成器的视图控制器委托并异步运行该函数之后,我做了一些测试。但是,它不起作用。我将视图控制器设置为初始视图控制器,但它仍然不起作用,因此在导航中不是问题,加载时间仍然很长。

import UIKit
import AVFoundation

class StartViewController: UIViewController, AVAudioRecorderDelegate {

    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var recordButton: UIButton!
    let synth = AVSpeechSynthesizer()
    var myUtterance = AVSpeechUtterance(string: "")
    var number = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        synth.delegate? = self as! AVSpeechSynthesizerDelegate
        number = 0
        DispatchQueue.global(qos: .userInitiated).async       {self.speakText(int: number)}
        self.number = self.number + 1
    }

    @IBAction func recordTapped(_ sender: UIButton) {
        speakText(int: number)
        number = number + 1
    }

    func speakText(int: Int) {

    myUtterance = AVSpeechUtterance(string: "the number is \(int)")
    myUtterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
    synth.speak(myUtterance)

    }

}

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,多线程有效。刚试过自己。下面的工作代码,请测试并确认。依靠单独的线程进行语音总是好的。

if (result instanceOf <SomeSubtype>) {
     <SomeSubtype> resultCasted = (<SomeSubtype>) result;
}

加号,要在显示视图时调用语音,请从import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var recordButton: UIButton! var number = 0 @IBAction func recordTapped(_ sender: UIButton) { questionLabel.text = "\(number)" speakTest(int: number) number += 1 } override func viewDidLoad() { super.viewDidLoad() number = 0 questionLabel.text = "\(number)" DispatchQueue.global(qos: .userInitiated).async { self.speakTest(int: self.number) } // speakTest(int: number) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func speakTest(int: Int) { let utterance = AVSpeechUtterance(string: "Number is \(int)") let synth = AVSpeechSynthesizer() synth.speak(utterance) } } viewWillAppear()而不是viewDidAppear()调用,因为后者在调用时调用一次应用程序在前台。