Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions LoopFollow/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
}

Expand Down
49 changes: 41 additions & 8 deletions LoopFollow/Controllers/AlarmSound.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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")
}
Expand All @@ -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)")
}
Expand Down Expand Up @@ -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)")
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
}

Expand Down
9 changes: 2 additions & 7 deletions LoopFollow/Controllers/SpeakBG.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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)
}
}
45 changes: 45 additions & 0 deletions LoopFollow/Controllers/SpeechOutput.swift
Original file line number Diff line number Diff line change
@@ -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()
}
}
22 changes: 0 additions & 22 deletions LoopFollow/ViewControllers/MainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)")
}
}
}
}