Looking for help understanding why setting audioSession.setActive(false) in the delegate function speechSynthesizer(_:didFinish:) always fails in the sample below.
import Foundation
import AVFoundation
class Speaker: NSObject, AVSpeechSynthesizerDelegate, @unchecked Sendable {
static let shared = Speaker()
let audioSession = AVAudioSession.sharedInstance()
let synthesizer = AVSpeechSynthesizer()
override init() {
super.init()
synthesizer.delegate = self
try? audioSession.setCategory(.playback, options: [.duckOthers])
}
func speakChat(text: String) {
let utterance = AVSpeechUtterance(string: text)
utterance.rate = 0.5
utterance.volume = 1.0
try? audioSession.setActive(true)
synthesizer.speak(utterance)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
do {
try audioSession.setActive(false)
} catch {
print(error.localizedDescription)
}
}
}