From 615c992f9ceaa6dc7afa0d38895907b5c9c72b0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Sun, 1 Nov 2026 15:32:01 +0100 Subject: [PATCH 1/4] Release the audio session after alarms and spoken BG so other audio returns to full volume --- LoopFollow/Controllers/AlarmSound.swift | 22 +++++++++++++++++++ .../ViewControllers/MainViewController.swift | 14 +----------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/LoopFollow/Controllers/AlarmSound.swift b/LoopFollow/Controllers/AlarmSound.swift index fafd2bf6f..6f6d8cdec 100644 --- a/LoopFollow/Controllers/AlarmSound.swift +++ b/LoopFollow/Controllers/AlarmSound.swift @@ -100,6 +100,27 @@ 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. + /// While Silent Tune's loop holds the session, it stays active with the + /// mixable category that loop uses. + static func releaseAudioSession() { + guard !isPlaying 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() { @@ -318,6 +339,7 @@ class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate { AlarmSound.playNextWithDelay() } else { Observable.shared.alarmSoundPlaying.value = false + AlarmSound.releaseAudioSession() } } diff --git a/LoopFollow/ViewControllers/MainViewController.swift b/LoopFollow/ViewControllers/MainViewController.swift index dce0b6611..025ecb6f3 100644 --- a/LoopFollow/ViewControllers/MainViewController.swift +++ b/LoopFollow/ViewControllers/MainViewController.swift @@ -1266,18 +1266,6 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { extension MainViewController: AVSpeechSynthesizerDelegate { func speechSynthesizer(_: AVSpeechSynthesizer, didFinish _: AVSpeechUtterance) { - let appState = UIApplication.shared.applicationState - let isSilentTuneMode = Storage.shared.backgroundRefreshType.value == .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)") - } - } + AlarmSound.releaseAudioSession() } } From 99bd1757e02bdbcaa3295f4ac3847e063e4b0801 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Fri, 6 Nov 2026 22:32:27 +0100 Subject: [PATCH 2/4] Put the output volume back after each alarm sound, including between delayed repeats --- LoopFollow/Controllers/AlarmSound.swift | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/LoopFollow/Controllers/AlarmSound.swift b/LoopFollow/Controllers/AlarmSound.swift index 6f6d8cdec..65817b209 100644 --- a/LoopFollow/Controllers/AlarmSound.swift +++ b/LoopFollow/Controllers/AlarmSound.swift @@ -173,11 +173,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") } @@ -196,9 +191,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)") } @@ -233,6 +226,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)") } @@ -281,6 +275,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 @@ -336,9 +343,11 @@ 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() } } From 650194d2a8987f11346cd5f5bad071a126ccb923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Sat, 14 Nov 2026 17:50:50 +0100 Subject: [PATCH 3/4] Keep the audio session while spoken BG is talking when an alarm ends --- LoopFollow/Controllers/AlarmSound.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/LoopFollow/Controllers/AlarmSound.swift b/LoopFollow/Controllers/AlarmSound.swift index 65817b209..f40301fdc 100644 --- a/LoopFollow/Controllers/AlarmSound.swift +++ b/LoopFollow/Controllers/AlarmSound.swift @@ -105,10 +105,12 @@ class AlarmSound { /// 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. - /// While Silent Tune's loop holds the session, it stays active with the - /// mixable category that loop uses. + /// 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 else { return } + guard !isPlaying, MainViewController.shared?.speechSynthesizer.isSpeaking != true else { return } let session = AVAudioSession.sharedInstance() do { From b1f5a45991982d33226da4d0f9ac0e8b38f2de70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Sat, 14 Nov 2026 18:08:58 +0100 Subject: [PATCH 4/4] Speak the Speak BG quick action through the shared speech output so other audio is ducked and comes back --- LoopFollow/Application/AppDelegate.swift | 6 +-- LoopFollow/Controllers/AlarmSound.swift | 2 +- LoopFollow/Controllers/SpeakBG.swift | 9 +--- LoopFollow/Controllers/SpeechOutput.swift | 45 +++++++++++++++++++ .../ViewControllers/MainViewController.swift | 10 ----- 5 files changed, 51 insertions(+), 21 deletions(-) create mode 100644 LoopFollow/Controllers/SpeechOutput.swift diff --git a/LoopFollow/Application/AppDelegate.swift b/LoopFollow/Application/AppDelegate.swift index 9a061cc1f..c6496250e 100644 --- a/LoopFollow/Application/AppDelegate.swift +++ b/LoopFollow/Application/AppDelegate.swift @@ -225,8 +225,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) { @@ -250,7 +248,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 f40301fdc..a7dca576c 100644 --- a/LoopFollow/Controllers/AlarmSound.swift +++ b/LoopFollow/Controllers/AlarmSound.swift @@ -110,7 +110,7 @@ class AlarmSound { /// 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, MainViewController.shared?.speechSynthesizer.isSpeaking != true else { return } + guard !isPlaying, !SpeechOutput.shared.isSpeaking else { return } let session = AVAudioSession.sharedInstance() do { diff --git a/LoopFollow/Controllers/SpeakBG.swift b/LoopFollow/Controllers/SpeakBG.swift index ee003ce49..0268d5ddf 100644 --- a/LoopFollow/Controllers/SpeakBG.swift +++ b/LoopFollow/Controllers/SpeakBG.swift @@ -142,12 +142,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 } @@ -175,6 +170,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 025ecb6f3..e4e3e9712 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 @@ -408,8 +406,6 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { updateQuickActions() - speechSynthesizer.delegate = self - // Check configuration and show appropriate UI if isDataSourceConfigured() { // Data source configured - show loading overlay @@ -1263,9 +1259,3 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { } } } - -extension MainViewController: AVSpeechSynthesizerDelegate { - func speechSynthesizer(_: AVSpeechSynthesizer, didFinish _: AVSpeechUtterance) { - AlarmSound.releaseAudioSession() - } -}