每当我导航到此视图控制器时,由于某种原因,其中的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)
}
}