Add SwiftAudioEx playback utility
This commit is contained in:
1 parent
d9a996aa98
commit
5ff510cd3f
5 files changed
+418
-2
No files matched your search
@@ -0,0 +1,314 @@
|
||||
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 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] = [:]
|
||||
|
||||
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()
|
||||
player.play()
|
||||
errorMessage = nil
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
refreshState()
|
||||
}
|
||||
|
||||
func pause() {
|
||||
player.pause()
|
||||
refreshState()
|
||||
}
|
||||
|
||||
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 }
|
||||
|
||||
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
|
||||
}
|
||||
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() {
|
||||
player.clear()
|
||||
tracksByItemID.removeAll()
|
||||
isPlaying = false
|
||||
currentTrack = nil
|
||||
upcomingTracks = []
|
||||
previousTracks = []
|
||||
elapsedTime = 0
|
||||
duration = 0
|
||||
errorMessage = nil
|
||||
}
|
||||
|
||||
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
|
||||
self?.isPlaying = state == .playing || state == .buffering
|
||||
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 = 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user