Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassMedia/Media/GlassAudioPlayback.swift8// Module : SPGlassMedia9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Observation43import AVFoundation4445/// The playback engine a ``GlassAudioPlayer`` displays and drives.46///47/// Conforming types are `@Observable` classes isolated to the main actor: the view reads the four state48/// properties and SwiftUI updates it when they change. ``GlassAVAudioPlayback`` is the AVFoundation49/// implementation; tests and previews use a fake.50@MainActor51public protocol GlassAudioPlayback: AnyObject, Observable {52 /// Whether audio is currently playing.53 var isPlaying: Bool { get }54 /// Position in seconds.55 var currentTime: TimeInterval { get }56 /// Length in seconds; 0 while it is unknown.57 var duration: TimeInterval { get }58 /// False when there is nothing playable (no item, failed item). The transport is then disabled.59 var isAvailable: Bool { get }6061 func play()62 func pause()63 /// Moves to `time` seconds. The player view clamps the value to `0...duration` before calling.64 func seek(to time: TimeInterval)65}6667/// AVFoundation-backed playback for ``GlassAudioPlayer``.68///69/// ```swift70/// @State private var playback = GlassAVAudioPlayback(url: episodeURL)71/// GlassAudioPlayer(playback: playback, title: "Episode 12")72/// ```73///74/// - Playback never starts by itself: only ``play()`` starts it.75/// - The audio session category is left untouched. On iOS the host calls76/// ``configureAudioSessionForPlayback()`` (or sets its own category) when it wants background-capable playback.77/// - On iOS an `AVAudioSession` interruption pauses playback; it resumes afterwards only when78/// ``resumesAfterInterruption`` is true and the system says resuming is appropriate.79/// - Reaching the end stops playback; the next ``play()`` starts again from the beginning.80@MainActor81@Observable82public final class GlassAVAudioPlayback: GlassAudioPlayback {83 public private(set) var isPlaying = false84 public private(set) var currentTime: TimeInterval = 085 public private(set) var duration: TimeInterval = 086 public private(set) var isAvailable = false8788 /// Whether playback resumes after an interruption that the system marks as resumable. Defaults to true.89 public var resumesAfterInterruption = true9091 /// The underlying player, for example to bind its `volume` to a ``GlassVolumeControl``.92 @ObservationIgnored public let player: AVPlayer9394 @ObservationIgnored private var timeObserver: Any?95 @ObservationIgnored private var statusObservation: NSKeyValueObservation?96 @ObservationIgnored private var notificationTokens: [any NSObjectProtocol] = []97 @ObservationIgnored private var loadTask: Task<Void, Never>?98 @ObservationIgnored private var wasPlayingWhenInterrupted = false99 @ObservationIgnored private var reachedEnd = false100101 /// Wraps an existing player. The player is not started, and its current item (if any) is inspected asynchronously.102 public init(player: AVPlayer, updateInterval: TimeInterval = 0.25) {103 self.player = player104 observe(updateInterval: updateInterval)105 loadCurrentItem()106 }107108 /// Creates a player for a local or remote URL. Nothing is played until ``play()``.109 public convenience init(url: URL, updateInterval: TimeInterval = 0.25) {110 self.init(player: AVPlayer(playerItem: AVPlayerItem(url: url)), updateInterval: updateInterval)111 }112113 isolated deinit {114 loadTask?.cancel()115 statusObservation?.invalidate()116 if let timeObserver {117 player.removeTimeObserver(timeObserver)118 }119 for token in notificationTokens {120 NotificationCenter.default.removeObserver(token)121 }122 }123124 public func play() {125 guard isAvailable else { return }126 if reachedEnd {127 reachedEnd = false128 currentTime = 0129 player.seek(to: .zero)130 }131 player.play()132 }133134 public func pause() {135 player.pause()136 }137138 public func seek(to time: TimeInterval) {139 guard isAvailable else { return }140 let target = GlassPlaybackMath.clampedSeek(time, duration: duration)141 reachedEnd = false142 currentTime = target143 player.seek(to: CMTime(seconds: target, preferredTimescale: 600))144 }145146 /// Replaces the current item. Playback stays paused.147 public func replaceItem(with url: URL?) {148 player.pause()149 player.replaceCurrentItem(with: url.map { AVPlayerItem(url: $0) })150 currentTime = 0151 duration = 0152 reachedEnd = false153 loadCurrentItem()154 }155156 #if os(iOS)157 /// Sets the shared audio session to the `.playback` category. GlassKit never calls this itself: the host158 /// decides whether its audio should continue with the silent switch on and in the background.159 public static func configureAudioSessionForPlayback() throws {160 try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)161 }162 #endif163164 // MARK: Observation of the player165166 private func observe(updateInterval: TimeInterval) {167 let interval = CMTime(seconds: max(updateInterval, 0.05), preferredTimescale: 600)168 timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in169 let seconds = time.seconds170 MainActor.assumeIsolated {171 self?.timeChanged(seconds)172 }173 }174 statusObservation = player.observe(\.timeControlStatus, options: [.initial, .new]) { [weak self] player, _ in175 let playing = player.timeControlStatus != .paused176 Task { @MainActor in177 self?.isPlaying = playing178 }179 }180 let center = NotificationCenter.default181 notificationTokens.append(center.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: nil, queue: .main) { [weak self] notification in182 let item = notification.object as? AVPlayerItem183 let identifier = item.map(ObjectIdentifier.init)184 MainActor.assumeIsolated {185 self?.itemEnded(identifier)186 }187 })188 notificationTokens.append(center.addObserver(forName: AVPlayerItem.failedToPlayToEndTimeNotification, object: nil, queue: .main) { [weak self] notification in189 let identifier = (notification.object as? AVPlayerItem).map(ObjectIdentifier.init)190 MainActor.assumeIsolated {191 self?.itemFailed(identifier)192 }193 })194 #if os(iOS)195 notificationTokens.append(center.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { [weak self] notification in196 guard let event = Self.interruptionEvent(from: notification.userInfo) else { return }197 MainActor.assumeIsolated {198 self?.interrupted(event)199 }200 })201 #endif202 }203204 private func timeChanged(_ seconds: TimeInterval) {205 guard seconds.isFinite else { return }206 currentTime = duration > 0 ? GlassPlaybackMath.clampedSeek(seconds, duration: duration) : max(seconds, 0)207 }208209 private func isCurrentItem(_ identifier: ObjectIdentifier?) -> Bool {210 guard let identifier, let current = player.currentItem else { return false }211 return ObjectIdentifier(current) == identifier212 }213214 private func itemEnded(_ identifier: ObjectIdentifier?) {215 guard isCurrentItem(identifier) else { return }216 player.pause()217 reachedEnd = true218 if duration > 0 { currentTime = duration }219 }220221 private func itemFailed(_ identifier: ObjectIdentifier?) {222 guard isCurrentItem(identifier) else { return }223 player.pause()224 isAvailable = false225 }226227 private func loadCurrentItem() {228 loadTask?.cancel()229 guard let item = player.currentItem else {230 isAvailable = false231 return232 }233 let asset = item.asset234 loadTask = Task { [weak self] in235 do {236 let (playable, length) = try await asset.load(.isPlayable, .duration)237 guard !Task.isCancelled else { return }238 self?.isAvailable = playable239 self?.duration = GlassPlaybackMath.sanitizedDuration(length.seconds)240 } catch {241 guard !Task.isCancelled else { return }242 self?.isAvailable = false243 self?.duration = 0244 }245 }246 }247248 #if os(iOS)249 private func interrupted(_ event: GlassAudioInterruptionEvent) {250 if event == .began { wasPlayingWhenInterrupted = isPlaying }251 switch GlassAudioInterruptionPolicy.action(for: event, wasPlayingWhenInterrupted: wasPlayingWhenInterrupted, resumesAfterInterruption: resumesAfterInterruption) {252 case .pause: pause()253 case .resume: play()254 case .none: break255 }256 if event != .began { wasPlayingWhenInterrupted = false }257 }258259 nonisolated private static func interruptionEvent(from userInfo: [AnyHashable: Any]?) -> GlassAudioInterruptionEvent? {260 guard let raw = userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,261 let type = AVAudioSession.InterruptionType(rawValue: raw) else { return nil }262 switch type {263 case .began:264 return .began265 case .ended:266 let options = AVAudioSession.InterruptionOptions(rawValue: userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)267 return .ended(shouldResume: options.contains(.shouldResume))268 @unknown default:269 return nil270 }271 }272 #endif273}274