Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassMedia/Media/GlassVolumeControl.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/// Volume of the application's own playback: a mute button and the system `Slider`.48///49/// ```swift50/// @State private var volume = 0.851///52/// GlassVolumeControl(volume: $volume)53/// .onChange(of: volume) { _, level in player.volume = Float(level) }54/// ```55///56/// The binding is a level from 0 to 1 that the host applies to its player (for example `AVPlayer.volume`).57/// Muting sets the level to 0 and remembers the previous one, which unmuting restores.58///59/// This control does not touch the system volume. On iOS the system volume is only reachable through60/// `MPVolumeView`, which the host places itself; no public API sets it programmatically.61public struct GlassVolumeControl: View {62 @GlassThemed private var theme63 @Binding private var volume: Double64 @State private var rememberedLevel: Double65 private let showsValue: Bool66 @Environment(\.isEnabled) private var isEnabled6768 /// - Parameters:69 /// - volume: level of the application's playback, 0 to 1. Values outside the range are clamped.70 /// - unmuteLevel: level restored by the first unmute when the control starts muted.71 /// - showsValue: shows the level as a whole percentage after the slider.72 public init(volume: Binding<Double>, unmuteLevel: Double = GlassVolumeState.defaultUnmuteLevel, showsValue: Bool = false) {73 _volume = volume74 _rememberedLevel = State(initialValue: GlassVolumeState.clamped(unmuteLevel))75 self.showsValue = showsValue76 }7778 private var state: GlassVolumeState {79 GlassVolumeState(level: volume, rememberedLevel: rememberedLevel)80 }8182 public var body: some View {83 HStack(spacing: theme.spacing.xs) {84 Button {85 apply(state.togglingMute())86 } label: {87 Label(GlassL10n.string(state.isMuted ? .unmute : .mute), systemImage: state.symbolName)88 .labelStyle(.iconOnly)89 .font(.system(size: theme.metrics.iconSize(.regular), weight: .medium))90 .foregroundStyle(theme.color(state.isMuted ? .textSecondary : .textPrimary))91 .contentTransition(.symbolEffect(.replace))92 // The widest speaker symbol sets the width, so the slider does not move with the level.93 .frame(width: theme.metrics.iconSize(.large) + 8, alignment: .leading)94 .glassMinimumHitTarget()95 .contentShape(Rectangle())96 }97 .buttonStyle(.plain)98 .help(GlassL10n.string(state.isMuted ? .unmute : .mute))99100 Slider(101 value: Binding(get: { state.level }, set: { apply(state.settingLevel($0)) }),102 in: 0...1103 ) {104 Text(GlassL10n.string(.volume))105 }106 .labelsHidden()107 .accessibilityLabel(Text(GlassL10n.string(.volume)))108 .accessibilityValue(Text(state.spokenValue()))109110 if showsValue {111 Text(state.level.formatted(.percent.precision(.fractionLength(0))))112 .font(theme.font(.caption).monospacedDigit().weight(.medium))113 .foregroundStyle(theme.color(.textSecondary))114 .frame(minWidth: 44, alignment: .trailing)115 .accessibilityHidden(true)116 }117 }118 .tint(theme.color(.primary))119 .opacity(isEnabled ? 1 : 0.55)120 }121122 private func apply(_ next: GlassVolumeState) {123 rememberedLevel = next.rememberedLevel124 volume = next.level125 }126}127128/// The state and reducer of ``GlassVolumeControl``.129public struct GlassVolumeState: Equatable, Sendable {130 /// Level restored by an unmute when no audible level was ever seen.131 public static let defaultUnmuteLevel = 0.5132133 /// Current level, 0 to 1.134 public let level: Double135 /// The last audible level, restored by unmuting.136 public let rememberedLevel: Double137138 public init(level: Double, rememberedLevel: Double = GlassVolumeState.defaultUnmuteLevel) {139 self.level = Self.clamped(level)140 let remembered = Self.clamped(rememberedLevel)141 self.rememberedLevel = remembered > 0 ? remembered : Self.defaultUnmuteLevel142 }143144 public var isMuted: Bool { level <= 0 }145146 /// Clamps to 0…1; NaN becomes 0.147 public static func clamped(_ value: Double) -> Double {148 value.isNaN ? 0 : min(max(value, 0), 1)149 }150151 /// Mutes (remembering the current level) or unmutes (restoring the remembered one).152 public func togglingMute() -> GlassVolumeState {153 isMuted154 ? GlassVolumeState(level: rememberedLevel, rememberedLevel: rememberedLevel)155 : GlassVolumeState(level: 0, rememberedLevel: level)156 }157158 /// Moves the level, as the slider does. An audible level becomes the remembered one.159 public func settingLevel(_ newLevel: Double) -> GlassVolumeState {160 let next = Self.clamped(newLevel)161 return GlassVolumeState(level: next, rememberedLevel: next > 0 ? next : rememberedLevel)162 }163164 /// The speaker symbol for the level: slashed when muted, then one to three waves.165 public var symbolName: String {166 switch level {167 case ...0: "speaker.slash.fill"168 case ..<0.34: "speaker.wave.1.fill"169 case ..<0.67: "speaker.wave.2.fill"170 default: "speaker.wave.3.fill"171 }172 }173174 /// The level as a whole percentage, 0 to 100.175 public var percent: Int { Int((level * 100).rounded()) }176177 /// What VoiceOver reads as the value: "Muted" or the localised percentage.178 public func spokenValue(locale: Locale = .autoupdatingCurrent) -> String {179 isMuted ? GlassL10n.string(.muted) : level.formatted(.percent.precision(.fractionLength(0)).locale(locale))180 }181}182