Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/Audio/NowPlayingCenter.swift3// Description: Lock screen / Control Centre metadata and remote commands.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import MediaPlayer10#if canImport(UIKit)11import UIKit12public typealias PlatformImage = UIImage13#elseif canImport(AppKit)14import AppKit15public typealias PlatformImage = NSImage16#endif1718/// The system's media controls: lock screen, Control Centre, Dynamic Island, AirPods and headset buttons, CarPlay,19/// keyboard media keys. These are the standard controls of any audio app — no Live Activity is created to imitate them.20@MainActor21public final class NowPlayingCenter {22 public struct Handlers {23 public var play: @MainActor () -> Void24 public var pause: @MainActor () -> Void25 public var toggle: @MainActor () -> Void26 public var next: @MainActor () -> Void27 public var previous: @MainActor () -> Void28 public var seek: @MainActor (TimeInterval) -> Void29 public var toggleFavorite: @MainActor () -> Void30 public init(play: @escaping @MainActor () -> Void, pause: @escaping @MainActor () -> Void, toggle: @escaping @MainActor () -> Void, next: @escaping @MainActor () -> Void,31 previous: @escaping @MainActor () -> Void, seek: @escaping @MainActor (TimeInterval) -> Void, toggleFavorite: @escaping @MainActor () -> Void) {32 self.play = play; self.pause = pause; self.toggle = toggle; self.next = next; self.previous = previous; self.seek = seek; self.toggleFavorite = toggleFavorite33 }34 }35 private var info: [String: Any] = [:]36 private var artworkFor: String?37 public private(set) var isRegistered = false3839 public init() {}4041 public func register(_ h: Handlers) {42 let c = MPRemoteCommandCenter.shared()43 // Handlers may be called off the main thread: answer at once, act on the main actor.44 func on(_ command: MPRemoteCommand, _ action: @escaping @MainActor () -> Void) {45 command.isEnabled = true46 command.addTarget { _ in Task { @MainActor in action() }; return .success }47 }48 on(c.playCommand, h.play); on(c.pauseCommand, h.pause); on(c.togglePlayPauseCommand, h.toggle)49 on(c.nextTrackCommand, h.next); on(c.previousTrackCommand, h.previous)50 c.changePlaybackPositionCommand.isEnabled = true51 c.changePlaybackPositionCommand.addTarget { event in52 guard let e = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }53 let t = e.positionTime54 Task { @MainActor in h.seek(t) }55 return .success56 }57 c.likeCommand.isEnabled = true58 c.likeCommand.localizedTitle = "Favori"59 c.likeCommand.addTarget { _ in Task { @MainActor in h.toggleFavorite() }; return .success }60 for unused in [c.skipForwardCommand, c.skipBackwardCommand, c.seekForwardCommand, c.seekBackwardCommand, c.dislikeCommand, c.bookmarkCommand] { unused.isEnabled = false }61 isRegistered = true62 }6364 public func setTrack(_ t: Track?, artwork: PlatformImage?) {65 guard let t else { info = [:]; artworkFor = nil; MPNowPlayingInfoCenter.default().nowPlayingInfo = nil; return }66 var i: [String: Any] = [67 MPMediaItemPropertyTitle: t.title, MPMediaItemPropertyArtist: t.artistName, MPMediaItemPropertyAlbumTitle: t.albumTitle,68 MPMediaItemPropertyAlbumArtist: t.albumArtistName, MPMediaItemPropertyPlaybackDuration: t.duration,69 MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue, MPMediaItemPropertyPersistentID: NSNumber(value: UInt64(truncatingIfNeeded: t.id.hashValue)),70 ]71 if let n = t.trackNo { i[MPMediaItemPropertyAlbumTrackNumber] = n }72 if let g = t.genre { i[MPMediaItemPropertyGenre] = g }73 // Keep the previous cover while the new one loads only when it is the same album.74 if let artwork { i[MPMediaItemPropertyArtwork] = Self.mediaArtwork(artwork); artworkFor = t.artworkId }75 else if artworkFor == t.artworkId, let old = info[MPMediaItemPropertyArtwork] { i[MPMediaItemPropertyArtwork] = old }76 for k in [MPNowPlayingInfoPropertyElapsedPlaybackTime, MPNowPlayingInfoPropertyPlaybackRate, MPNowPlayingInfoPropertyDefaultPlaybackRate,77 MPNowPlayingInfoPropertyPlaybackQueueIndex, MPNowPlayingInfoPropertyPlaybackQueueCount] { if let v = info[k] { i[k] = v } }78 info = i79 MPNowPlayingInfoCenter.default().nowPlayingInfo = info80 MPRemoteCommandCenter.shared().likeCommand.isActive = t.favorite81 }8283 public func setProgress(position: TimeInterval, duration: TimeInterval, playing: Bool) {84 guard !info.isEmpty else { return }85 info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = position86 info[MPNowPlayingInfoPropertyPlaybackRate] = playing ? 1.0 : 0.087 info[MPNowPlayingInfoPropertyDefaultPlaybackRate] = 1.088 if duration > 0 { info[MPMediaItemPropertyPlaybackDuration] = duration }89 let center = MPNowPlayingInfoCenter.default()90 center.nowPlayingInfo = info91 #if os(macOS)92 center.playbackState = playing ? .playing : .paused93 #endif94 }9596 public func setQueue(index: Int, count: Int) {97 guard !info.isEmpty else { return }98 info[MPNowPlayingInfoPropertyPlaybackQueueIndex] = index99 info[MPNowPlayingInfoPropertyPlaybackQueueCount] = count100 MPNowPlayingInfoCenter.default().nowPlayingInfo = info101 }102103 public var currentInfo: [String: Any] { info }104105 /// The system calls the artwork handler on a queue of its own: the closure must not inherit the main actor.106 private nonisolated static func mediaArtwork(_ image: PlatformImage) -> MPMediaItemArtwork {107 MPMediaItemArtwork(boundsSize: image.size) { _ in image }108 }109}110