PulseCanvas / app · pulsecanvas.ai / mobile / MobilePlaybackSession.swift
| 1 | import AVFoundation |
| 2 | import Combine |
| 3 | import MediaPlayer |
| 4 | |
| 5 | /// One playback session for Studio and Radio, including lock-screen controls. |
| 6 | @MainActor final class MobilePlaybackSession { |
| 7 | private weak var audio: AudioController? |
| 8 | private weak var radio: RadioController? |
| 9 | private var observations = Set<AnyCancellable>() |
| 10 | private var commands: [(MPRemoteCommand, Any)] = [] |
| 11 | private var hasPlayed = false |
| 12 | private var resumeAfterInterruption = false |
| 13 | |
| 14 | init(audio: AudioController, radio: RadioController) { |
| 15 | self.audio = audio; self.radio = radio |
| 16 | let center = MPRemoteCommandCenter.shared() |
| 17 | bind(center.playCommand) { $0.play() } |
| 18 | bind(center.pauseCommand) { $0.pause() } |
| 19 | bind(center.togglePlayPauseCommand) { session in |
| 20 | if session.audio?.isPlaying == true || session.radio?.isActive == true && session.radio?.isPlaybackRequested == true { |
| 21 | session.pause() |
| 22 | } else { session.play() } |
| 23 | } |
| 24 | bind(center.nextTrackCommand) { $0.radio?.next() } |
| 25 | let seek = center.changePlaybackPositionCommand.addTarget { [weak self] event in |
| 26 | guard let event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed } |
| 27 | let seconds = event.positionTime |
| 28 | Task { @MainActor [weak self] in self?.seek(seconds) } |
| 29 | return .success |
| 30 | } |
| 31 | commands.append((center.changePlaybackPositionCommand, seek)) |
| 32 | audio.objectWillChange.sink { [weak self] _ in |
| 33 | Task { @MainActor [weak self] in self?.publish() } |
| 34 | }.store(in: &observations) |
| 35 | radio.objectWillChange.sink { [weak self] _ in |
| 36 | Task { @MainActor [weak self] in self?.publish() } |
| 37 | }.store(in: &observations) |
| 38 | audio.visualizationUpdated.throttle(for: .seconds(1), scheduler: RunLoop.main, latest: true) |
| 39 | .sink { [weak self] _ in self?.publish() }.store(in: &observations) |
| 40 | NotificationCenter.default.publisher(for: AVAudioSession.interruptionNotification) |
| 41 | .receive(on: RunLoop.main).sink { [weak self] in self?.interruption($0) }.store(in: &observations) |
| 42 | NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification) |
| 43 | .receive(on: RunLoop.main).sink { [weak self] notification in |
| 44 | guard let raw = notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt, |
| 45 | AVAudioSession.RouteChangeReason(rawValue: raw) == .oldDeviceUnavailable else { return } |
| 46 | self?.pause() |
| 47 | }.store(in: &observations) |
| 48 | publish() |
| 49 | } |
| 50 | |
| 51 | private func bind(_ command: MPRemoteCommand, action: @escaping @MainActor (MobilePlaybackSession) -> Void) { |
| 52 | let token = command.addTarget { [weak self] _ in |
| 53 | Task { @MainActor [weak self] in if let self { action(self); self.publish() } } |
| 54 | return .success |
| 55 | } |
| 56 | commands.append((command, token)) |
| 57 | } |
| 58 | private func play() { |
| 59 | guard let audio else { return } |
| 60 | if radio?.isActive == true { |
| 61 | if radio?.isPlaybackRequested != true { radio?.togglePlayback() } |
| 62 | } else if !audio.isPlaying { audio.playPause() } |
| 63 | } |
| 64 | private func pause() { |
| 65 | resumeAfterInterruption = false |
| 66 | if radio?.isActive == true { radio?.pause() } else { audio?.pause() } |
| 67 | } |
| 68 | private func seek(_ seconds: Double) { |
| 69 | guard let audio, audio.duration > 0, seconds.isFinite else { return } |
| 70 | if radio?.isActive == true { radio?.seek(fraction: seconds / audio.duration) } |
| 71 | else { audio.seek(fraction: seconds / audio.duration) } |
| 72 | publish() |
| 73 | } |
| 74 | private func interruption(_ notification: Notification) { |
| 75 | guard let raw = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, |
| 76 | let type = AVAudioSession.InterruptionType(rawValue: raw) else { return } |
| 77 | if type == .began { |
| 78 | let shouldResume = audio?.isPlaying == true || radio?.isActive == true && radio?.isPlaybackRequested == true |
| 79 | pause(); resumeAfterInterruption = shouldResume |
| 80 | } else if type == .ended { |
| 81 | let options = AVAudioSession.InterruptionOptions(rawValue: notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0) |
| 82 | let shouldResume = resumeAfterInterruption && options.contains(.shouldResume) |
| 83 | resumeAfterInterruption = false |
| 84 | if shouldResume { play() } |
| 85 | } |
| 86 | publish() |
| 87 | } |
| 88 | private func publish() { |
| 89 | guard let audio, let radio else { return } |
| 90 | hasPlayed = hasPlayed || audio.isPlaying |
| 91 | let ready = hasPlayed && audio.selectedURL != nil |
| 92 | let center = MPRemoteCommandCenter.shared() |
| 93 | center.playCommand.isEnabled = ready |
| 94 | center.pauseCommand.isEnabled = ready |
| 95 | center.togglePlayPauseCommand.isEnabled = ready |
| 96 | center.nextTrackCommand.isEnabled = ready && radio.isActive && !radio.isLoading |
| 97 | center.previousTrackCommand.isEnabled = false |
| 98 | center.changePlaybackPositionCommand.isEnabled = ready && (!radio.isActive || radio.canSeek) |
| 99 | guard ready else { |
| 100 | // Loading the demo paused must not take over another app's controls. |
| 101 | if hasPlayed { MPNowPlayingInfoCenter.default().nowPlayingInfo = nil } |
| 102 | return |
| 103 | } |
| 104 | MPNowPlayingInfoCenter.default().nowPlayingInfo = [ |
| 105 | MPMediaItemPropertyTitle: radio.isActive ? radio.currentTrack?.title ?? "PulseCanvas Radio" : audio.title, |
| 106 | MPMediaItemPropertyAlbumTitle: "PulseCanvas Studio", |
| 107 | MPMediaItemPropertyPlaybackDuration: audio.duration, |
| 108 | MPNowPlayingInfoPropertyElapsedPlaybackTime: audio.playbackSeconds, |
| 109 | MPNowPlayingInfoPropertyPlaybackRate: audio.isPlaying ? 1.0 : 0.0, |
| 110 | MPNowPlayingInfoPropertyDefaultPlaybackRate: 1.0, |
| 111 | MPNowPlayingInfoPropertyIsLiveStream: false |
| 112 | ] |
| 113 | } |
| 114 | deinit { for (command, token) in commands { command.removeTarget(token) } } |
| 115 | } |