350 lines
12 KiB
Swift
350 lines
12 KiB
Swift
import Combine
|
|
import AVFAudio
|
|
import Foundation
|
|
import SwiftAudioEx
|
|
import UIKit
|
|
|
|
enum PlayerRepeatMode: CaseIterable {
|
|
case off
|
|
case one
|
|
case all
|
|
}
|
|
|
|
/// App-owned playback state and actions backed by SwiftAudioEx.
|
|
@MainActor
|
|
final class PlayerManager: ObservableObject {
|
|
@Published private(set) var currentTrack: Track?
|
|
@Published private(set) var upcomingTracks: [Track] = []
|
|
@Published private(set) var previousTracks: [Track] = []
|
|
@Published private(set) var isPlaying = false
|
|
@Published private(set) var elapsedTime: TimeInterval = 0
|
|
@Published private(set) var duration: TimeInterval = 0
|
|
@Published private(set) var errorMessage: String?
|
|
@Published private(set) var isMiniPlayerCompact = false
|
|
@Published var repeatMode: PlayerRepeatMode = .off {
|
|
didSet { applyRepeatMode() }
|
|
}
|
|
@Published var volume: Double {
|
|
didSet {
|
|
let clamped = min(1, max(0, volume))
|
|
if clamped != volume {
|
|
volume = clamped
|
|
return
|
|
}
|
|
player.volume = Float(clamped)
|
|
UserDefaults.standard.set(clamped, forKey: Self.volumeStorageKey)
|
|
}
|
|
}
|
|
|
|
private static let volumeStorageKey = "music-v2-player-volume"
|
|
private let player = QueuedAudioPlayer()
|
|
private let apiConfiguration: APIConfiguration
|
|
private var tracksByItemID: [ObjectIdentifier: Track] = [:]
|
|
private var playbackIntent: Bool?
|
|
|
|
init() {
|
|
self.apiConfiguration = APIConfiguration()
|
|
let storedVolume = UserDefaults.standard.object(forKey: Self.volumeStorageKey) as? Double
|
|
volume = min(1, max(0, storedVolume ?? 0.5))
|
|
player.volume = Float(volume)
|
|
player.automaticallyUpdateNowPlayingInfo = true
|
|
player.remoteCommands = [.play, .pause, .togglePlayPause, .next, .previous, .changePlaybackPosition]
|
|
installEventListeners()
|
|
}
|
|
|
|
func play() {
|
|
do {
|
|
try AudioSessionController.shared.set(category: .playback)
|
|
try AudioSessionController.shared.activateSession()
|
|
playbackIntent = true
|
|
player.play()
|
|
isPlaying = true
|
|
errorMessage = nil
|
|
} catch {
|
|
playbackIntent = nil
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
refreshState()
|
|
}
|
|
|
|
func pause() {
|
|
playbackIntent = false
|
|
isPlaying = false
|
|
player.pause()
|
|
}
|
|
|
|
func play(_ track: Track) {
|
|
play([track], startingAt: 0, shuffled: false)
|
|
}
|
|
|
|
func play(_ tracks: [Track], startingAt index: Int = 0, shuffled: Bool = false) {
|
|
guard !tracks.isEmpty else { clear(); return }
|
|
guard tracks.indices.contains(index) else { return }
|
|
isMiniPlayerCompact = false
|
|
|
|
let orderedTracks: [Track]
|
|
if shuffled {
|
|
let selected = tracks[index]
|
|
orderedTracks = [selected] + tracks.enumerated()
|
|
.filter { $0.offset != index }
|
|
.map(\.element)
|
|
.shuffled()
|
|
} else {
|
|
orderedTracks = Array(tracks[index...])
|
|
}
|
|
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
let items = orderedTracks.compactMap(makeAudioItem(for:))
|
|
guard !items.isEmpty else {
|
|
errorMessage = "Could not create an audio URL for this track."
|
|
return
|
|
}
|
|
playbackIntent = true
|
|
player.add(items: items, playWhenReady: true)
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
}
|
|
|
|
func next() {
|
|
player.next()
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
}
|
|
|
|
func previous() {
|
|
if player.currentTime > 5 {
|
|
seek(to: 0)
|
|
} else {
|
|
player.previous()
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
}
|
|
}
|
|
|
|
func seek(to seconds: TimeInterval) {
|
|
player.seek(to: min(max(0, seconds), max(duration, 0)))
|
|
elapsedTime = min(max(0, seconds), max(duration, 0))
|
|
}
|
|
|
|
func addToQueue(_ track: Track) {
|
|
guard let item = makeAudioItem(for: track) else { return }
|
|
if player.currentItem == nil {
|
|
player.add(item: item, playWhenReady: false)
|
|
} else {
|
|
player.add(item: item)
|
|
}
|
|
refreshState()
|
|
}
|
|
|
|
func playNext(_ track: Track) {
|
|
guard let item = makeAudioItem(for: track) else { return }
|
|
guard player.currentItem != nil else {
|
|
player.add(item: item, playWhenReady: true)
|
|
refreshState()
|
|
return
|
|
}
|
|
do {
|
|
try player.add(items: [item], at: player.currentIndex + 1)
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
refreshState()
|
|
}
|
|
|
|
func playQueuedTrack(at index: Int) {
|
|
guard player.items.indices.contains(index) else { return }
|
|
do {
|
|
try player.jumpToItem(atIndex: index, playWhenReady: true)
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func moveQueuedTrack(from sourceIndex: Int, to destinationIndex: Int) {
|
|
guard player.items.indices.contains(sourceIndex),
|
|
player.items.indices.contains(destinationIndex)
|
|
else { return }
|
|
do {
|
|
try player.moveItem(fromIndex: sourceIndex, toIndex: destinationIndex)
|
|
refreshState()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func removeQueuedTrack(at index: Int) {
|
|
guard player.items.indices.contains(index) else { return }
|
|
let item = player.items[index]
|
|
do {
|
|
_ = try player.removeItem(at: index)
|
|
tracksByItemID.removeValue(forKey: ObjectIdentifier(item as AnyObject))
|
|
refreshState()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func clear() {
|
|
playbackIntent = nil
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
isPlaying = false
|
|
currentTrack = nil
|
|
upcomingTracks = []
|
|
previousTracks = []
|
|
elapsedTime = 0
|
|
duration = 0
|
|
errorMessage = nil
|
|
}
|
|
|
|
func artworkURL(for track: Track) -> URL? {
|
|
guard case .value(let album) = track.album else { return nil }
|
|
return apiConfiguration.mediaURL(for: album.file)
|
|
}
|
|
|
|
func compactMiniPlayerForDownwardScroll() {
|
|
isMiniPlayerCompact = true
|
|
}
|
|
|
|
func shuffleUpcoming() {
|
|
let currentIndex = player.currentIndex
|
|
guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return }
|
|
|
|
let targetOrder = Array(player.items.dropFirst(currentIndex + 1)).shuffled()
|
|
for (offset, target) in targetOrder.enumerated() {
|
|
let targetID = ObjectIdentifier(target as AnyObject)
|
|
guard let existingIndex = player.items.firstIndex(where: {
|
|
ObjectIdentifier($0 as AnyObject) == targetID
|
|
}) else { continue }
|
|
let targetIndex = currentIndex + 1 + offset
|
|
if existingIndex != targetIndex {
|
|
try? player.moveItem(fromIndex: existingIndex, toIndex: targetIndex)
|
|
}
|
|
}
|
|
refreshState()
|
|
}
|
|
|
|
func cycleRepeat() {
|
|
switch repeatMode {
|
|
case .off: repeatMode = .one
|
|
case .one: repeatMode = .all
|
|
case .all: repeatMode = .off
|
|
}
|
|
}
|
|
|
|
private func applyRepeatMode() {
|
|
switch repeatMode {
|
|
case .off: player.repeatMode = .off
|
|
case .one: player.repeatMode = .track
|
|
case .all: player.repeatMode = .queue
|
|
}
|
|
}
|
|
|
|
private func makeAudioItem(for track: Track) -> DefaultAudioItem? {
|
|
guard let url = apiConfiguration.audioURL(for: track) else { return nil }
|
|
let artistNames = track.artists.compactMap { reference -> String? in
|
|
guard case .value(let artist) = reference else { return nil }
|
|
return artist.name
|
|
}
|
|
let albumName: String?
|
|
if case .value(let album) = track.album {
|
|
albumName = album.name
|
|
} else {
|
|
albumName = nil
|
|
}
|
|
let item = DefaultAudioItem(
|
|
audioUrl: url.absoluteString,
|
|
artist: artistNames.joined(separator: ", "),
|
|
title: track.name,
|
|
albumTitle: albumName,
|
|
sourceType: .stream
|
|
)
|
|
tracksByItemID[ObjectIdentifier(item)] = track
|
|
return item
|
|
}
|
|
|
|
private func installEventListeners() {
|
|
player.event.stateChange.addListener(self) { [weak self] state in
|
|
Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
switch state {
|
|
case .playing:
|
|
if self.playbackIntent != false {
|
|
self.playbackIntent = nil
|
|
self.isPlaying = true
|
|
}
|
|
case .paused:
|
|
self.playbackIntent = nil
|
|
self.isPlaying = false
|
|
case .buffering:
|
|
if self.playbackIntent != false { self.isPlaying = true }
|
|
case .stopped, .idle, .failed, .ended:
|
|
self.playbackIntent = nil
|
|
self.isPlaying = false
|
|
case .loading, .ready:
|
|
break
|
|
}
|
|
self.refreshState()
|
|
}
|
|
}
|
|
player.event.currentItem.addListener(self) { [weak self] _ in
|
|
Task { @MainActor [weak self] in
|
|
self?.refreshState()
|
|
self?.loadArtwork(for: self?.player.currentItem)
|
|
}
|
|
}
|
|
player.event.secondElapse.addListener(self) { [weak self] elapsed in
|
|
Task { @MainActor [weak self] in
|
|
self?.elapsedTime = elapsed
|
|
self?.duration = self?.player.duration ?? 0
|
|
}
|
|
}
|
|
player.event.updateDuration.addListener(self) { [weak self] duration in
|
|
Task { @MainActor [weak self] in self?.duration = duration }
|
|
}
|
|
player.event.fail.addListener(self) { [weak self] error in
|
|
Task { @MainActor [weak self] in
|
|
self?.errorMessage = error?.localizedDescription ?? "Playback failed."
|
|
self?.isPlaying = false
|
|
}
|
|
}
|
|
}
|
|
|
|
private func refreshState() {
|
|
currentTrack = track(for: player.currentItem)
|
|
upcomingTracks = player.nextItems.compactMap { track(for: $0) }
|
|
previousTracks = player.previousItems.compactMap { track(for: $0) }
|
|
elapsedTime = player.currentTime
|
|
duration = player.duration
|
|
isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering)
|
|
}
|
|
|
|
private func track(for item: AudioItem?) -> Track? {
|
|
guard let item else { return nil }
|
|
return tracksByItemID[ObjectIdentifier(item as AnyObject)]
|
|
}
|
|
|
|
private func loadArtwork(for item: AudioItem?) {
|
|
guard let item,
|
|
let track = track(for: item),
|
|
let audioItem = item as? DefaultAudioItem,
|
|
case .value(let album) = track.album,
|
|
let url = apiConfiguration.mediaURL(for: album.file)
|
|
else { return }
|
|
|
|
Task {
|
|
guard let (data, _) = try? await URLSession.shared.data(from: url),
|
|
let image = UIImage(data: data)
|
|
else { return }
|
|
audioItem.artwork = image
|
|
guard let currentItem = player.currentItem,
|
|
ObjectIdentifier(currentItem as AnyObject) == ObjectIdentifier(item as AnyObject)
|
|
else { return }
|
|
player.loadNowPlayingMetaValues()
|
|
}
|
|
}
|
|
}
|