diff --git a/LoopFollow/Application/AppDelegate.swift b/LoopFollow/Application/AppDelegate.swift index 66b06478d..3064082a2 100644 --- a/LoopFollow/Application/AppDelegate.swift +++ b/LoopFollow/Application/AppDelegate.swift @@ -239,8 +239,6 @@ extension Notification.Name { /// the window; this class only handles the events UIKit routes to the scene /// delegate instead of the application delegate. final class AppSceneDelegate: NSObject, UIWindowSceneDelegate { - private let speechSynthesizer = AVSpeechSynthesizer() - /// A quick action used to cold-launch the app arrives in the connection /// options; windowScene(_:performActionFor:) is not called for that launch. func scene(_: UIScene, willConnectTo _: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { @@ -264,7 +262,9 @@ final class AppSceneDelegate: NSObject, UIWindowSceneDelegate { } Storage.shared.speakBG.value.toggle() let message = Storage.shared.speakBG.value ? "BG Speak is now on" : "BG Speak is now off" - speechSynthesizer.speak(AVSpeechUtterance(string: message)) + if SpeechOutput.shared.activateAudioSession() { + SpeechOutput.shared.speak(AVSpeechUtterance(string: message)) + } return true } diff --git a/LoopFollow/Controllers/AlarmSound.swift b/LoopFollow/Controllers/AlarmSound.swift index fd575351b..a2789510f 100644 --- a/LoopFollow/Controllers/AlarmSound.swift +++ b/LoopFollow/Controllers/AlarmSound.swift @@ -100,6 +100,29 @@ class AlarmSound { audioPlayer = nil restoreSystemOutputVolume() + releaseAudioSession() + } + + /// Hands the audio session back once LoopFollow has nothing left to play, so + /// audio from other apps that was ducked or interrupted returns to full volume. + /// Spoken BG that is still talking keeps the session; deactivating under it + /// cuts the speech and leaves the synthesizer stuck, and its didFinish + /// releases the session instead. While Silent Tune's loop holds the session, + /// it stays active with the mixable category that loop uses. + static func releaseAudioSession() { + guard !isPlaying, !SpeechOutput.shared.isSpeaking else { return } + + let session = AVAudioSession.sharedInstance() + do { + if MainViewController.shared?.backgroundTask.isPlaying == true { + try session.setCategory(.playback, mode: .default, options: .mixWithOthers) + } else { + try session.setActive(false, options: .notifyOthersOnDeactivation) + } + } catch { + let nsError = error as NSError + LogManager.shared.log(category: .alarm, message: "AlarmSound - audio session release failed [code \(nsError.code)]: \(error.localizedDescription)") + } } static func playTest() { @@ -152,11 +175,6 @@ class AlarmSound { // When repeatDelay > 0, we play once and then use the delegate to schedule the next play with delay audioPlayer!.numberOfLoops = (repeating && repeatDelay == 0) ? -1 : 0 - // Store existing volume - if systemOutputVolumeBeforeOverride == nil { - systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume - } - if !audioPlayer!.prepareToPlay() { LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play") } @@ -175,9 +193,7 @@ class AlarmSound { LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play") } - if Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume { - MPVolumeView.setVolume(Storage.shared.alarmConfiguration.value.forcedOutputVolume) - } + applySystemOutputVolumeOverride() } catch { LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)") } @@ -212,6 +228,7 @@ class AlarmSound { if audioPlayer!.play() { Observable.shared.alarmSoundPlaying.value = true + applySystemOutputVolumeOverride() } else { LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play (delayed repeat)") } @@ -260,6 +277,19 @@ class AlarmSound { } } + /// Raises the output volume of the current route to the configured alarm volume, + /// remembering the volume it had so it can be put back between repeats and on stop. + fileprivate static func applySystemOutputVolumeOverride() { + guard Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume else { + return + } + + if systemOutputVolumeBeforeOverride == nil { + systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume + } + MPVolumeView.setVolume(Storage.shared.alarmConfiguration.value.forcedOutputVolume) + } + fileprivate static func restoreSystemOutputVolume() { guard Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume else { return @@ -315,9 +345,12 @@ class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate { // If we're repeating with delay, schedule the next play if AlarmSound.repeatDelay > 0 { + AlarmSound.restoreSystemOutputVolume() AlarmSound.playNextWithDelay() } else { Observable.shared.alarmSoundPlaying.value = false + AlarmSound.restoreSystemOutputVolume() + AlarmSound.releaseAudioSession() } } diff --git a/LoopFollow/Controllers/SpeakBG.swift b/LoopFollow/Controllers/SpeakBG.swift index ac42acbe3..e3f4b227a 100644 --- a/LoopFollow/Controllers/SpeakBG.swift +++ b/LoopFollow/Controllers/SpeakBG.swift @@ -81,12 +81,7 @@ extension MainViewController { } // 2. Now that we know we need to speak, activate the audio session. - let audioSession = AVAudioSession.sharedInstance() - do { - try audioSession.setCategory(.playback, mode: .default, options: .duckOthers) - try audioSession.setActive(true) - } catch { - LogManager.shared.log(category: .general, message: "speakBG, Failed to set up audio session: \(error)") + guard SpeechOutput.shared.activateAudioSession() else { return } @@ -104,6 +99,6 @@ extension MainViewController { // 5. Speak. let speechUtterance = AVSpeechUtterance(string: announcementText) speechUtterance.voice = AVSpeechSynthesisVoice(language: voiceLanguageCode) - speechSynthesizer.speak(speechUtterance) + SpeechOutput.shared.speak(speechUtterance) } } diff --git a/LoopFollow/Controllers/SpeechOutput.swift b/LoopFollow/Controllers/SpeechOutput.swift new file mode 100644 index 000000000..2da3c5f8f --- /dev/null +++ b/LoopFollow/Controllers/SpeechOutput.swift @@ -0,0 +1,45 @@ +// LoopFollow +// SpeechOutput.swift + +import AVFoundation +import Foundation + +/// The speech synthesizer shared by spoken BG and the Speak BG quick action. +/// Speech ducks other audio, and the audio session is handed back through +/// AlarmSound.releaseAudioSession() when an utterance finishes. +final class SpeechOutput: NSObject, AVSpeechSynthesizerDelegate { + static let shared = SpeechOutput() + + private let synthesizer = AVSpeechSynthesizer() + + var isSpeaking: Bool { + synthesizer.isSpeaking + } + + override private init() { + super.init() + synthesizer.delegate = self + } + + /// Activates the audio session with ducking of other audio. + /// - Returns: False when the session could not be activated. + func activateAudioSession() -> Bool { + let audioSession = AVAudioSession.sharedInstance() + do { + try audioSession.setCategory(.playback, mode: .default, options: .duckOthers) + try audioSession.setActive(true) + return true + } catch { + LogManager.shared.log(category: .general, message: "speakBG, Failed to set up audio session: \(error)") + return false + } + } + + func speak(_ utterance: AVSpeechUtterance) { + synthesizer.speak(utterance) + } + + func speechSynthesizer(_: AVSpeechSynthesizer, didFinish _: AVSpeechUtterance) { + AlarmSound.releaseAudioSession() + } +} diff --git a/LoopFollow/ViewControllers/MainViewController.swift b/LoopFollow/ViewControllers/MainViewController.swift index 1df99a134..0faacab26 100644 --- a/LoopFollow/ViewControllers/MainViewController.swift +++ b/LoopFollow/ViewControllers/MainViewController.swift @@ -49,8 +49,6 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { private var setupNightscoutButton: UIButton! private var setupDexcomButton: UIButton! - let speechSynthesizer = AVSpeechSynthesizer() - // Variables for BG Charts var firstGraphLoad: Bool = true var currentOverride = 1.0 @@ -411,8 +409,6 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { updateQuickActions() - speechSynthesizer.delegate = self - // Check configuration and show appropriate UI if isDataSourceConfigured() { // Data source configured - show loading overlay @@ -1362,21 +1358,3 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { } } } - -extension MainViewController: AVSpeechSynthesizerDelegate { - func speechSynthesizer(_: AVSpeechSynthesizer, didFinish _: AVSpeechUtterance) { - let appState = UIApplication.shared.applicationState - let isSilentTuneMode = BackgroundRefreshType.inEffect == .silentTune - - if isSilentTuneMode, appState == .background { - LogManager.shared.log(category: .general, message: "Silent tune active in background; not deactivating session.", isDebug: true) - } else { - do { - try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) - LogManager.shared.log(category: .general, message: "Audio session deactivated after speech.", isDebug: true) - } catch { - LogManager.shared.log(category: .alarm, message: "Failed to deactivate audio session: \(error)") - } - } - } -}