// Playing a voice note out of the archive. // // ONE player for the whole conversation, so starting a second note stops the // first — two recordings talking over each other is never what somebody meant. // The bytes are asked for the way every attachment's are: `media.ensure` // answers a PATH on this device, fetching only when the file is not here yet, // and the player reads the file. Nothing is streamed and nothing is sent. import AVFoundation import CottonKit import Foundation import Observation @MainActor @Observable final class VoiceNotePlayer: NSObject, AVAudioPlayerDelegate { /// The key of the note playing, or nil. private(set) var playingKey: String? private(set) var pausedKey: String? var duration: Double { player?.duration ?? 0 } var elapsed: Double { max(positionFloor, player?.currentTime ?? 0) } /// The key being fetched before it can play. private(set) var loadingKey: String? /// The key whose bytes could not be had, so the note can say so. private(set) var unavailableKey: String? private(set) var unplayableKey: String? @ObservationIgnored private var player: AVAudioPlayer? @ObservationIgnored private var generation = 0 @ObservationIgnored private var positionFloor: Double = 0 /// How far through the playing note is, 0…1. var progress: Double { guard let player, player.duration > 0 else { return 0 } return min(1, max(0, elapsed / player.duration)) } /// Play, pause or resume the same recording. A different key replaces it. func toggle(_ key: String?, media: PhotosMediaSource) async { guard let key, !key.isEmpty else { return } if playingKey == key { let position = elapsed player?.pause() positionFloor = max(position, player?.currentTime ?? position) playingKey = nil pausedKey = key return } if pausedKey == key, let player { // Re-establish the paused offset before restarting the audio // queue; its resumed clock can otherwise report an earlier frame. let position = elapsed player.currentTime = position // The restarted queue briefly reports a frame before the pause // point. Hold the displayed position until its clock catches up. positionFloor = position if player.play() { pausedKey = nil playingKey = key } return } stop() let asked = generation loadingKey = key unavailableKey = nil unplayableKey = nil defer { if generation == asked { loadingKey = nil } } var path = await media.path(for: key) guard generation == asked, !Task.isCancelled else { return } if path == nil { path = try? await media.ensure(key) } guard generation == asked, !Task.isCancelled else { return } guard let path else { unavailableKey = key return } guard let made = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) else { unplayableKey = key return } #if os(iOS) // Heard with the ringer silenced: a voice note somebody taps is a // thing they asked to hear. try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio) try? AVAudioSession.sharedInstance().setActive(true) #endif made.delegate = self player = made if made.play() { playingKey = key } else { unplayableKey = key } } func stop() { generation += 1 loadingKey = nil player?.stop() player = nil positionFloor = 0 playingKey = nil pausedKey = nil } nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { let finished = ObjectIdentifier(player) Task { @MainActor in guard self.player.map(ObjectIdentifier.init) == finished else { return } self.stop() } } }