AVSpeechSynthesiser 窃听 ViewDidLoad 功能

AVSpeechSynthesiser bugging ViewDidLoad function

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

UPDATE 在分配语音合成器的视图控制器委托和异步 运行 函数之后,我做了一些更多的测试。但是,它不起作用。我把view controller设置为initial view controller还是不行,所以不是导航问题,加载时间还是很长。

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)

    }

}

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

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

Plus,要在视图出现时调用 Speech,请从 viewWillAppear()viewDidAppear() 而不是 viewDidLoad() 调用它,因为后者当应用程序在前台时被调用一次。