gpt4 book ai didi

swift - AVSpeechSynthesiser 窃听 ViewDidLoad 功能

转载 作者:行者123 更新时间:2023-11-28 14:44:42 25 4
gpt4 key购买 nike

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

更新 在分配语音合成器的 View Controller 委托(delegate)并异步运行函数后,我做了一些更多的测试。但是,它不起作用。我将 View Controller 设置为初始 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)
}
}

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

关于swift - AVSpeechSynthesiser 窃听 ViewDidLoad 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50365260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com