// 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 AVFoundationimportCottonKitimportFoundationimportObservation@MainActor@ObservablefinalclassVoiceNotePlayer: 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 privatevar player: AVAudioPlayer? @ObservationIgnored privatevar generation = 0 @ObservationIgnored privatevar positionFloor: Double = 0/// How far through the playing note is, 0…1.var progress: Double {guardlet player, player.duration > 0else { return0 }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 {guardlet key, !key.isEmpty else { return }if playingKey == key {let position = elapsed player?.pause() positionFloor = max(position, player?.currentTime ?? position) playingKey = nil pausedKey = keyreturn }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 = positionif player.play() { pausedKey = nil playingKey = key }return } stop()let asked = generation loadingKey = key unavailableKey = nil unplayableKey = nildefer { 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 }guardlet path else { unavailableKey = keyreturn }guardlet made = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) else { unplayableKey = keyreturn } #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 = madeif 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 inguardself.player.map(ObjectIdentifier.init) == finished else { return }self.stop() } }}