首页 > 解决方案 > 为什么我的 AVFoundation Speech 不起作用?

问题描述

嘿伙计们,这是我的代码:

func configureSpeechButton() {
        contentView.addSubview(speechButton)
        speechButton.setImage(speechImage, for: .normal)
        speechButton.addTarget(self, action: #selector(speechButtontapped), for: .touchUpInside)
        
        //Constraints
        speechButton.translatesAutoresizingMaskIntoConstraints = false
        speechButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 40).isActive = true
        speechButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
        speechButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
        speechButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
        
    }
    
    @objc func speechButtontapped() {
        
        let speech = AVSpeechUtterance(string: "\(testSpeech)")
        speech.voice = AVSpeechSynthesisVoice(language: "de")
        
        let synth = AVSpeechSynthesizer()
        synth.speak(speech)
        
    }
    
    let testSpeech = "This is a test"

我将按钮放在滚动视图的内容视图上,有人能告诉我问题出在哪里吗?提前致谢

标签: swiftavfoundationsiri

解决方案


AVSpeechSynthesizer的超出范围。将其分配给成员变量以延长其生命周期。


推荐阅读