AVSpeech 结束时 SwiftUI 屏幕冻结

问题描述 投票:0回答:1

用户界面中有一个按钮,按下该按钮会播放简短的问候语。为了测试性能,我无休止地滚动屏幕的轮播。当声音说话时,一切都很好,但是,结束后约 1 秒,滚动停止,屏幕冻结 1 秒,然后再次恢复正常。我点击后删除了演讲,以测试它是否有其他逻辑,但一旦我这样做了,问题就消失了。

运行时,此消息将打印到控制台:

无法停用音频会话:会话停用失败

    struct UIScreen: View {
        let speechSynthesizer = SpeechSynthesizerManager()
        var body: some View {
            ZStack{
                CarouselView()
                Button {
                    speechSynthesizer.speak(say: "Pause")
                } label: {
                    Text("Press Me")
                }
            }
        }
    }

    import AVFoundation

    class SpeechSynthesizerManager: NSObject, AVSpeechSynthesizerDelegate {
        var synthesizer = AVSpeechSynthesizer()

        override init() {
            super.init()
            synthesizer.delegate = self
        }

        func speak(say: String) {
            DispatchQueue.global(qos: .userInitiated).async {
                do {
                    try AVAudioSession.sharedInstance().setCategory(.playback, options: [.duckOthers])
                    try AVAudioSession.sharedInstance().setActive(true)

                    let utterance = AVSpeechUtterance(string: say)
                    utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
                    utterance.rate = 0.5

                    DispatchQueue.main.async {
                        self.synthesizer.speak(utterance)
                    }
                } catch {
                    print("Audio session error: \(error.localizedDescription)")
                }
            }
        }

        func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
            do {
                try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
            } catch {
                print("Failed to deactivate audio session: \(error.localizedDescription)")
            }
        }
    }

我在主线程上运行,然后更新了代码以在后台线程上运行,但两者都导致了相同的问题并将相同的错误打印到控制台。

swift swiftui avfoundation avspeechsynthesizer
1个回答
0
投票

我希望这对你有帮助,尝试一次。

do {
            try audioSession.setCategory(.playback)
            try audioSession.setActive(false)
            print("Audio session reset and deactivated successfully")
        } catch let error {
            print("Error resetting and deactivating audio session: \(error.localizedDescription)")
        }
© www.soinside.com 2019 - 2024. All rights reserved.