0

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

更新在分配语音合成器的视图控制器委托并异步运行该功能后,我做了更多测试。但是,它不起作用。我将视图控制器设置为初始视图控制器,但它仍然不起作用,所以导航不是问题,加载时间仍然很长。

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)

    }

}
4

1 回答 1

1

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

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

另外,要在视图出现时调用 Speech,请从viewWillAppear()viewDidAppear()不调用它viewDidLoad(),因为后者在应用程序处于前台时调用一次。

于 2018-05-16T09:58:07.627 回答