SPB Git

Repository Public MIT

GlassAudioPlayer.swift 14.1 KB 344 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMedia/Media/GlassAudioPlayer.swift8// Module           : SPGlassMedia9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//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 SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// The two forms of a ``GlassAudioPlayer``.48public enum GlassAudioPlayerStyle: String, CaseIterable, Sendable {49    /// Artwork and titles, the seek track with both times, then the transport row. For a "now playing" area.50    case expanded51    /// One row (artwork, titles, play, skip forward) over a thin seek track. For a bar docked above a tab bar.52    case compact53}5455/// An audio transport on a glass surface: artwork and titles, a seek track with the times, play or pause and56/// the skip buttons.57///58/// ```swift59/// @State private var playback = GlassAVAudioPlayback(url: episodeURL)60///61/// GlassAudioPlayer(playback: playback, title: "Episode 12", subtitle: "The Glass Hour")62/// GlassAudioPlayer(playback: playback, title: "Episode 12", artwork: Image("cover"), style: .compact)63/// ```64///65/// The view owns no audio: it displays a ``GlassAudioPlayback`` and calls it. Playback never starts by itself.66/// While the user drags the seek track the position is previewed locally and the seek happens once, on release.67/// With a `waveform` the amplitude bars replace the rail and are scrubbed the same way.68public struct GlassAudioPlayer<Playback: GlassAudioPlayback>: View {69    @GlassThemed private var theme70    @Environment(\.layoutDirection) private var layoutDirection71    private let playback: Playback72    private let title: String?73    private let subtitle: String?74    private let skipInterval: TimeInterval75    private let artwork: Image?76    private let waveform: GlassWaveformData?77    private let style: GlassAudioPlayerStyle78    @State private var scrubTime: TimeInterval?7980    /// - Parameters:81    ///   - playback: the engine to display and drive.82    ///   - title: name of what is playing (data, shown verbatim).83    ///   - subtitle: secondary line such as the artist or the show.84    ///   - skipInterval: seconds skipped by the skip buttons. Symbols exist for 5, 10, 15, 30, 45, 60, 75 and 90.85    ///   - artwork: cover shown in the artwork tile, cropped to a square. Without one the tile shows a symbol.86    ///   - waveform: amplitudes of the recording; they replace the seek rail of the expanded style.87    ///   - style: ``GlassAudioPlayerStyle/expanded`` (default) or ``GlassAudioPlayerStyle/compact``.88    public init(89        playback: Playback,90        title: String? = nil,91        subtitle: String? = nil,92        skipInterval: TimeInterval = 15,93        artwork: Image? = nil,94        waveform: GlassWaveformData? = nil,95        style: GlassAudioPlayerStyle = .expanded96    ) {97        self.playback = playback98        self.title = title99        self.subtitle = subtitle100        self.skipInterval = max(skipInterval, 1)101        self.artwork = artwork102        self.waveform = waveform103        self.style = style104    }105106    public var body: some View {107        Group {108            switch style {109            case .expanded: expanded110            case .compact: compact111            }112        }113        .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))114    }115116    // MARK: Layouts117118    private var expanded: some View {119        VStack(alignment: .leading, spacing: theme.spacing.md) {120            HStack(spacing: theme.spacing.sm) {121                artworkTile(side: 60)122                titles123                Spacer(minLength: 0)124            }125            if playback.isAvailable {126                VStack(spacing: theme.spacing.xxs) {127                    seekTrack128                    times129                }130                transport131            } else {132                unavailable133            }134        }135        .padding(theme.spacing.md)136    }137138    private var compact: some View {139        VStack(spacing: 0) {140            HStack(spacing: theme.spacing.sm) {141                artworkTile(side: 44)142                titles143                Spacer(minLength: 0)144                if playback.isAvailable {145                    playButton(diameter: 40, symbolSize: 16)146                    skipButton(forward: true)147                } else {148                    Image(systemName: "speaker.slash")149                        .foregroundStyle(theme.color(.textSecondary))150                        .accessibilityLabel(Text(GlassL10n.string(.mediaUnavailable)))151                }152            }153            if playback.isAvailable {154                scrubber(trackHeight: 3)155            }156        }157        .padding(.horizontal, theme.spacing.sm)158        .padding(.top, theme.spacing.xs)159        .padding(.bottom, playback.isAvailable ? 0 : theme.spacing.xs)160    }161162    // MARK: Parts163164    private func artworkTile(side: CGFloat) -> some View {165        let shape = RoundedRectangle(cornerRadius: min(theme.radii.medium, side * 0.28), style: .continuous)166        return ZStack {167            if let artwork {168                artwork169                    .resizable()170                    .aspectRatio(contentMode: .fill)171            } else {172                theme.color(.primary).opacity(theme.isDark ? 0.28 : 0.14)173                Image(systemName: playback.isAvailable ? "waveform" : "speaker.slash.fill")174                    .font(.system(size: side * 0.36, weight: .semibold))175                    .foregroundStyle(theme.color(.primary))176            }177        }178        .frame(width: side, height: side)179        .clipShape(shape)180        .overlay(shape.strokeBorder(theme.color(.separator).opacity(0.6), lineWidth: 0.5))181        .saturation(playback.isAvailable ? 1 : 0.2)182        .opacity(playback.isAvailable ? 1 : 0.7)183        .accessibilityHidden(true)184    }185186    @ViewBuilder187    private var titles: some View {188        if title != nil || subtitle != nil {189            VStack(alignment: .leading, spacing: 2) {190                if let title {191                    Text(verbatim: title)192                        .font(theme.font(.headline))193                        .foregroundStyle(theme.color(.textPrimary))194                        .lineLimit(style == .compact ? 1 : 2)195                }196                if let subtitle {197                    Text(verbatim: subtitle)198                        .font(theme.font(style == .compact ? .caption : .callout))199                        .foregroundStyle(theme.color(.textSecondary))200                        .lineLimit(style == .compact ? 1 : 2)201                }202            }203            .multilineTextAlignment(.leading)204            .accessibilityElement(children: .combine)205        }206    }207208    private var unavailable: some View {209        Label(GlassL10n.string(.mediaUnavailable), systemImage: "exclamationmark.circle")210            .font(theme.font(.callout))211            .foregroundStyle(theme.color(.textSecondary))212    }213214    private var displayedTime: TimeInterval {215        GlassPlaybackMath.clampedSeek(scrubTime ?? playback.currentTime, duration: playback.duration)216    }217218    @ViewBuilder219    private var seekTrack: some View {220        if let waveform, !waveform.isEmpty {221            waveformTrack(waveform)222        } else {223            scrubber(trackHeight: 4)224        }225    }226227    private func scrubber(trackHeight: CGFloat) -> some View {228        GlassScrubber(229            currentTime: playback.currentTime,230            duration: playback.duration,231            tint: theme.color(.primary),232            rail: theme.color(.textSecondary).opacity(0.28),233            trackHeight: trackHeight,234            scrubTime: $scrubTime235        ) { playback.seek(to: $0) }236        .disabled(playback.duration <= 0)237    }238239    /// The amplitude bars as the seek track: dragging previews the position, releasing seeks.240    private func waveformTrack(_ data: GlassWaveformData) -> some View {241        GeometryReader { proxy in242            GlassWaveform(data, progress: GlassPlaybackMath.fraction(currentTime: displayedTime, duration: playback.duration), minimumHeight: 40)243                .contentShape(Rectangle())244                .gesture(245                    DragGesture(minimumDistance: 0)246                        .onChanged { value in247                            let position = GlassScrubberMath.fraction(at: value.location.x, width: proxy.size.width, isRightToLeft: layoutDirection == .rightToLeft)248                            scrubTime = GlassScrubberMath.time(fraction: position, duration: playback.duration)249                        }250                        .onEnded { _ in251                            if let target = scrubTime { playback.seek(to: target) }252                            scrubTime = nil253                        },254                    isEnabled: playback.duration > 0255                )256        }257        .frame(height: 44)258        .accessibilityRepresentation {259            Slider(260                value: Binding(get: { displayedTime }, set: { playback.seek(to: GlassPlaybackMath.clampedSeek($0, duration: playback.duration)) }),261                in: 0...max(GlassPlaybackMath.sanitizedDuration(playback.duration), 1),262                step: GlassScrubberMath.step(duration: playback.duration)263            ) {264                Text(GlassL10n.string(.playbackPosition))265            }266            .accessibilityValue(Text(GlassPlaybackMath.spokenPosition(currentTime: displayedTime, duration: playback.duration)))267        }268    }269270    private var times: some View {271        HStack {272            Text(verbatim: GlassPlaybackMath.formatted(displayedTime))273                .accessibilityLabel(Text(GlassL10n.string(.elapsedTime)))274                .accessibilityValue(Text(verbatim: GlassPlaybackMath.formatted(displayedTime)))275            Spacer(minLength: theme.spacing.xs)276            Text(verbatim: GlassPlaybackMath.formattedRemaining(currentTime: displayedTime, duration: playback.duration))277                .accessibilityLabel(Text(GlassL10n.string(.remainingTime)))278                .accessibilityValue(Text(verbatim: GlassPlaybackMath.formatted(GlassPlaybackMath.remaining(currentTime: displayedTime, duration: playback.duration))))279        }280        .font(theme.font(.caption).monospacedDigit())281        .foregroundStyle(theme.color(.textSecondary))282    }283284    private var transport: some View {285        HStack(spacing: theme.spacing.xl) {286            skipButton(forward: false)287            playButton(diameter: 56, symbolSize: 22)288            skipButton(forward: true)289        }290        .frame(maxWidth: .infinity)291    }292293    private func playButton(diameter: CGFloat, symbolSize: CGFloat) -> some View {294        let label: GlassL10n.Key = playback.isPlaying ? .pause : .play295        return Button {296            if playback.isPlaying { playback.pause() } else { playback.play() }297        } label: {298            Image(systemName: playback.isPlaying ? "pause.fill" : "play.fill")299                .font(.system(size: symbolSize, weight: .semibold))300                .foregroundStyle(theme.onColor(.primary))301                // The play triangle is optically off-centre: nudge it towards its tip.302                .offset(x: playback.isPlaying ? 0 : symbolSize * 0.07)303                .frame(width: diameter, height: diameter)304                .background(theme.color(.primary), in: Circle())305                .contentTransition(.symbolEffect(.replace))306                .glassMinimumHitTarget()307                .contentShape(Circle())308        }309        .buttonStyle(.plain)310        .keyboardShortcut(.space, modifiers: [])311        .accessibilityLabel(Text(GlassL10n.string(label)))312        .help(GlassL10n.string(label))313    }314315    private func skipButton(forward: Bool) -> some View {316        let label: GlassL10n.Key = forward ? .skipForward : .skipBack317        return Button {318            playback.seek(to: GlassPlaybackMath.skip(from: playback.currentTime, by: forward ? skipInterval : -skipInterval, duration: playback.duration))319        } label: {320            Image(systemName: GlassAudioPlayerSymbols.skip(skipInterval, forward: forward))321                .font(.system(size: style == .compact ? 20 : 24, weight: .regular))322                .foregroundStyle(theme.color(.textPrimary))323                .glassMinimumHitTarget()324                .contentShape(Rectangle())325        }326        .buttonStyle(.plain)327        .accessibilityLabel(Text(GlassL10n.string(label)))328        .help(GlassL10n.string(label))329    }330}331332/// Symbol names used by ``GlassAudioPlayer``.333public enum GlassAudioPlayerSymbols {334    /// Skip intervals that have a dedicated numbered SF Symbol.335    public static let numberedIntervals: Set<Int> = [5, 10, 15, 30, 45, 60, 75, 90]336337    /// The skip symbol for an interval: numbered when SF Symbols has one, otherwise the plain arrow.338    public static func skip(_ interval: TimeInterval, forward: Bool) -> String {339        let base = forward ? "goforward" : "gobackward"340        let seconds = Int(interval.rounded())341        return numberedIntervals.contains(seconds) ? "\(base).\(seconds)" : base342    }343}344
Files main
Menu

Theme