Glimmer / app · glimmertoday.ai / native / Glimmer / GalleryAmbience.swift
| 1 | import AVFAudio |
| 2 | import Foundation |
| 3 | import Observation |
| 4 | |
| 5 | /// Play one field recording at a time. Scheduling decoded PCM keeps the sound |
| 6 | /// independent of video item changes, decoder priming and network latency. |
| 7 | @MainActor @Observable |
| 8 | final class GalleryAmbience { |
| 9 | static let shared = GalleryAmbience() |
| 10 | private(set) var owner: UUID? |
| 11 | private var preparation: Task<Void, Never>? |
| 12 | private var engine: AVAudioEngine? |
| 13 | |
| 14 | func stop(for id: UUID) { |
| 15 | guard owner == id else { return } |
| 16 | preparation?.cancel() |
| 17 | preparation = nil |
| 18 | engine?.stop() |
| 19 | engine = nil |
| 20 | owner = nil |
| 21 | } |
| 22 | |
| 23 | func toggle(id: UUID, url: URL, onFailure: @escaping () -> Void) { |
| 24 | let wasPlaying = owner == id |
| 25 | if let owner { stop(for: owner) } |
| 26 | guard !wasPlaying else { return } |
| 27 | owner = id |
| 28 | preparation = Task { |
| 29 | do { |
| 30 | // The field recording has its own immutable URL. Audio starts after its |
| 31 | // complete track is locally available; subsequent loops need no network. |
| 32 | let (tmp, response) = try await URLSession.shared.download(from: url) |
| 33 | defer { try? FileManager.default.removeItem(at: tmp) } |
| 34 | guard let http = response as? HTTPURLResponse, http.statusCode == 200, |
| 35 | http.url == url else { throw CocoaError(.fileReadCorruptFile) } |
| 36 | let file = try AVAudioFile(forReading: tmp) |
| 37 | guard file.length > 0, file.length <= Int64(file.processingFormat.sampleRate * 30), |
| 38 | (1...2).contains(file.processingFormat.channelCount), |
| 39 | let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)) |
| 40 | else { throw CocoaError(.fileReadCorruptFile) } |
| 41 | try file.read(into: buffer) |
| 42 | try Task.checkCancellation() |
| 43 | guard owner == id else { return } |
| 44 | let engine = AVAudioEngine() |
| 45 | let player = AVAudioPlayerNode() |
| 46 | engine.attach(player) |
| 47 | engine.connect(player, to: engine.mainMixerNode, format: buffer.format) |
| 48 | player.scheduleBuffer(buffer, at: nil, options: .loops, completionHandler: nil) |
| 49 | #if os(iOS) |
| 50 | try AVAudioSession.sharedInstance().setCategory(.ambient) |
| 51 | #endif |
| 52 | try engine.start() |
| 53 | self.engine = engine |
| 54 | player.play() |
| 55 | } catch { |
| 56 | guard !Task.isCancelled, owner == id else { return } |
| 57 | stop(for: id) |
| 58 | onFailure() |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | } |