SPB Git

Repository Public License

SoundPlayer.swift 12.8 KB 261 lines swift

1// ORIX Alarm2// File: App/Wake/SoundPlayer.swift3// Description: Foreground audio engine: sound previews, the looping wake soundscape with its volume envelope, interface effects, session handling.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import AVFoundation910/// Preview and soundscape playback (foreground only).11///12/// Scope, on purpose:13/// - No background audio mode is declared. Everything here plays only while the app is open in the foreground; the14///   alarm itself is rung by iOS (AlarmKit), not by this class.15/// - The player only ever changes its own gain. It never touches the system volume: whatever it plays is limited by16///   the volume the user set on the iPhone (`deviceVolume` lets the UI say so).17@Observable18final class SoundPlayer {19    static let shared = SoundPlayer()2021    /// Identifier of the sound being previewed, if any.22    private(set) var previewingID: String?23    /// Identifier of the soundscape loaded for the progressive wake, if any.24    private(set) var soundscapeID: String?25    /// Last intensity requested for the soundscape (0...1).26    private(set) var soundscapeIntensity: Double = 027    /// True while another app or a call holds the audio (the soundscape is paused).28    private(set) var isInterrupted = false2930    /// Longest preview of a soundscape; alarm sounds are previewed once through.31    static let soundscapePreviewSeconds: TimeInterval = 303233    @ObservationIgnored private var previewPlayer: AVAudioPlayer?34    @ObservationIgnored private var previewTask: Task<Void, Never>?35    @ObservationIgnored private var soundscapePlayer: AVAudioPlayer?36    @ObservationIgnored private var soundscapeStopTask: Task<Void, Never>?37    @ObservationIgnored private var effectPlayers: [SoundFX.Effect: [AVAudioPlayer]] = [:]38    @ObservationIgnored private var effectTurn: [SoundFX.Effect: Int] = [:]39    @ObservationIgnored private var sessionUse = SessionUse.none40    @ObservationIgnored private var observers: [any NSObjectProtocol] = []4142    private enum SessionUse { case none, effects, playback }4344    private init() { observeSession() }4546    /// Hardware volume currently set by the user (0...1). Read-only: the app cannot and does not change it.47    var deviceVolume: Double { Double(AVAudioSession.sharedInstance().outputVolume) }4849    // MARK: Previews5051    func togglePreview(alarmSoundID id: String) {52        togglePreview(id: id, asset: SoundCatalog.alarmSounds.first { $0.id == id }, limit: nil, volume: 1)53    }5455    func togglePreview(soundscapeID id: String) {56        togglePreview(id: id, asset: SoundCatalog.soundscapes.first { $0.id == id }, limit: Self.soundscapePreviewSeconds, volume: 0.85)57    }5859    func stopPreview() {60        previewTask?.cancel(); previewTask = nil61        previewPlayer?.stop(); previewPlayer = nil62        previewingID = nil63        releaseSessionIfIdle()64    }6566    private func togglePreview(id: String, asset: SoundAsset?, limit: TimeInterval?, volume: Float) {67        let wasPlaying = previewingID == id68        stopPreview()   // one preview at a time69        guard !wasPlaying, let asset, let player = makePlayer(fileName: asset.fileName), activatePlayback() else { return }70        player.volume = volume71        guard player.play() else { releaseSessionIfIdle(); return }72        previewPlayer = player73        previewingID = id74        previewTask = Task { [weak self] in75            let started = ContinuousClock.now76            while !Task.isCancelled {77                try? await Task.sleep(for: .milliseconds(200))78                guard let self, !Task.isCancelled, self.previewPlayer === player else { return }79                let elapsed = ContinuousClock.now - started80                if let limit, elapsed >= .seconds(limit - 1.2), player.volume == volume { player.setVolume(0, fadeDuration: 1.2) }81                // The file reached its end, the fade-out is over, or the system stopped the player.82                if !player.isPlaying || (limit.map { elapsed >= .seconds($0) } ?? false) { self.stopPreview(); return }83            }84        }85    }8687    // MARK: Soundscape (progressive wake)8889    /// Loads a soundscape and starts it silently, looping. Raise it with `setIntensity`. `nil` stops it.90    func setSoundscape(id: String?) {91        guard let id else { return stopSoundscape(fade: 0) }92        if soundscapeID == id, soundscapePlayer != nil { soundscapeStopTask?.cancel(); soundscapeStopTask = nil; return }93        stopSoundscape(fade: 0)94        guard let asset = SoundCatalog.soundscapes.first(where: { $0.id == id }), let player = makePlayer(fileName: asset.fileName) else { return }95        player.numberOfLoops = -196        player.volume = 097        soundscapePlayer = player98        soundscapeID = id99        soundscapeIntensity = 0100        if activatePlayback() { player.play() }101    }102103    /// Sets the soundscape level (0 silent ... 1 full) with a short ramp, so successive calls from the wake timeline never step audibly.104    func setIntensity(_ intensity: Double, ramp: TimeInterval = 1.0) {105        let value = min(max(intensity, 0), 1)106        soundscapeIntensity = value107        guard let player = soundscapePlayer, !isInterrupted else { return }108        if !player.isPlaying, value > 0, activatePlayback() { player.play() }109        player.setVolume(Self.gain(value), fadeDuration: max(0.05, ramp))110    }111112    func stopSoundscape(fade: TimeInterval = 2.0) {113        soundscapeStopTask?.cancel(); soundscapeStopTask = nil114        guard let player = soundscapePlayer else { soundscapeID = nil; soundscapeIntensity = 0; return }115        soundscapeIntensity = 0116        guard fade > 0, player.isPlaying else { return finishSoundscapeStop() }117        player.setVolume(0, fadeDuration: fade)118        soundscapeStopTask = Task { [weak self] in119            try? await Task.sleep(for: .seconds(fade + 0.05))120            guard !Task.isCancelled, let self, self.soundscapePlayer === player else { return }121            self.finishSoundscapeStop()122        }123    }124125    /// Call when the app returns to the foreground: restarts a soundscape the system paused without asking us to resume.126    func resumeSoundscapeIfNeeded() {127        guard let player = soundscapePlayer, !player.isPlaying, soundscapeIntensity > 0, soundscapeStopTask == nil else { return }128        isInterrupted = false129        guard activatePlayback() else { return }130        player.volume = 0131        player.play()132        player.setVolume(Self.gain(soundscapeIntensity), fadeDuration: 2)133    }134135    private func finishSoundscapeStop() {136        soundscapeStopTask = nil137        soundscapePlayer?.stop(); soundscapePlayer = nil138        soundscapeID = nil139        releaseSessionIfIdle()140    }141142    /// Perceived loudness is far from linear in amplitude: a power law makes equal intensity steps sound like equal steps.143    private static func gain(_ intensity: Double) -> Float { Float(pow(intensity, 1.6)) }144145    // MARK: Interface effects146147    func prepareEffects() {148        for effect in SoundFX.Effect.allCases where effectPlayers[effect] == nil {149            // Two players per effect so a fast repeat overlaps instead of cutting the previous one.150            let pair = (0..<2).compactMap { _ in makePlayer(fileName: effect.fileName + ".caf") }151            pair.forEach { $0.volume = 0.7; $0.prepareToPlay() }152            effectPlayers[effect] = pair153        }154    }155156    func playEffect(_ effect: SoundFX.Effect) {157        if effectPlayers[effect] == nil { prepareEffects() }158        guard let pair = effectPlayers[effect], !pair.isEmpty else { return }159        if sessionUse == .none {160            // `.ambient` mixes with the user's music and follows the silent switch: right for incidental feedback.161            try? AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default, options: [.mixWithOthers])162            sessionUse = .effects163        }164        let turn = (effectTurn[effect] ?? 0) % pair.count165        effectTurn[effect] = turn + 1166        let player = pair[turn]167        player.currentTime = 0168        player.play()169    }170171    // MARK: Audio session172173    /// `.playback` is deliberate for previews and for the Nightstand soundscape: it is the category that keeps playing174    /// when the Ring/Silent switch is set to silent. A wake soundscape that the silent switch could mute would fail175    /// exactly the people who silence their phone at night. It is not mixable, so other apps' audio pauses while it176    /// plays and resumes when we deactivate with `.notifyOthersOnDeactivation`.177    private func activatePlayback() -> Bool {178        let session = AVAudioSession.sharedInstance()179        do {180            if sessionUse != .playback { try session.setCategory(.playback, mode: .default, options: []) }181            try session.setActive(true)182            sessionUse = .playback183            return true184        } catch {185            return false   // e.g. a phone call is in progress: stay silent rather than fight the system186        }187    }188189    private func releaseSessionIfIdle() {190        guard sessionUse == .playback, previewPlayer == nil, soundscapePlayer == nil else { return }191        try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)192        sessionUse = .none193    }194195    private func observeSession() {196        let center = NotificationCenter.default197        let session = AVAudioSession.sharedInstance()198        observers.append(center.addObserver(forName: AVAudioSession.interruptionNotification, object: session, queue: .main) { note in199            let type = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init(rawValue:))200            let options = AVAudioSession.InterruptionOptions(rawValue: note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)201            Task { @MainActor in SoundPlayer.shared.handleInterruption(type: type, shouldResume: options.contains(.shouldResume)) }202        })203        observers.append(center.addObserver(forName: AVAudioSession.routeChangeNotification, object: session, queue: .main) { note in204            let reason = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init(rawValue:))205            Task { @MainActor in SoundPlayer.shared.handleRouteChange(reason: reason) }206        })207        observers.append(center.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: session, queue: .main) { _ in208            Task { @MainActor in SoundPlayer.shared.handleMediaServicesReset() }209        })210    }211212    private func handleInterruption(type: AVAudioSession.InterruptionType?, shouldResume: Bool) {213        switch type {214        case .began:215            // A call, Siri, another app's alarm: the system has already silenced us. Remember it and stop asking to play.216            isInterrupted = true217            soundscapePlayer?.pause()218            stopPreview()219        case .ended:220            isInterrupted = false221            // Resume only when the system says it is appropriate; otherwise wait for `resumeSoundscapeIfNeeded()`.222            if shouldResume { resumeSoundscapeIfNeeded() }223        default: break224        }225    }226227    private func handleRouteChange(reason: AVAudioSession.RouteChangeReason?) {228        guard reason == .oldDeviceUnavailable else { return }229        // Headphones or a speaker went away. A preview stops (nobody wants a surprise on the loudspeaker). The wake230        // soundscape continues on the new route, since its job is to be heard, but it comes back from silence with a slow ramp.231        stopPreview()232        guard let player = soundscapePlayer, soundscapeIntensity > 0, !isInterrupted else { return }233        player.volume = 0234        if !player.isPlaying, activatePlayback() { player.play() }235        player.setVolume(Self.gain(soundscapeIntensity), fadeDuration: 3)236    }237238    /// The audio server restarted: every player is dead. Rebuild what was running.239    private func handleMediaServicesReset() {240        let scape = soundscapeID, level = soundscapeIntensity241        previewTask?.cancel(); previewTask = nil; previewPlayer = nil; previewingID = nil242        soundscapeStopTask?.cancel(); soundscapeStopTask = nil; soundscapePlayer = nil; soundscapeID = nil243        effectPlayers.removeAll()244        sessionUse = .none; isInterrupted = false245        if let scape { setSoundscape(id: scape); setIntensity(level, ramp: 2) }246    }247248    // MARK: Files249250    /// Sounds sit at the root of the app bundle (AlarmKit looks alarm sounds up there by name).251    static func url(forFileName fileName: String) -> URL? {252        let name = (fileName as NSString).deletingPathExtension, ext = (fileName as NSString).pathExtension253        return Bundle.main.url(forResource: name, withExtension: ext) ?? Bundle.main.url(forResource: name, withExtension: ext, subdirectory: "Sounds")254    }255256    private func makePlayer(fileName: String) -> AVAudioPlayer? {257        guard let url = Self.url(forFileName: fileName) else { return nil }258        return try? AVAudioPlayer(contentsOf: url)259    }260}261
Files main
Menu

Theme