Add SwiftAudioEx playback utility
This commit is contained in:
1 parent
d9a996aa98
commit
5ff510cd3f
5 files changed
+418
-2
No files matched your search
+54
@@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>$(PRODUCT_NAME)</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>$(MARKETING_VERSION)</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||||
|
<key>LSRequiresIPhoneOS</key>
|
||||||
|
<true/>
|
||||||
|
<key>UIBackgroundModes</key>
|
||||||
|
<array>
|
||||||
|
<string>audio</string>
|
||||||
|
</array>
|
||||||
|
<key>UIApplicationSceneManifest</key>
|
||||||
|
<dict>
|
||||||
|
<key>UIApplicationSupportsMultipleScenes</key>
|
||||||
|
<true/>
|
||||||
|
<key>UISceneConfigurations</key>
|
||||||
|
<dict/>
|
||||||
|
</dict>
|
||||||
|
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||||
|
<true/>
|
||||||
|
<key>UILaunchScreen</key>
|
||||||
|
<dict/>
|
||||||
|
<key>UIStatusBarStyle</key>
|
||||||
|
<string>UIStatusBarStyleDefault</string>
|
||||||
|
<key>UISupportedInterfaceOrientations</key>
|
||||||
|
<array>
|
||||||
|
<string>UIInterfaceOrientationPortrait</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||||
|
</array>
|
||||||
|
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||||
|
<array>
|
||||||
|
<string>UIInterfaceOrientationPortrait</string>
|
||||||
|
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -6,6 +6,10 @@
|
|||||||
objectVersion = 77;
|
objectVersion = 77;
|
||||||
objects = {
|
objects = {
|
||||||
|
|
||||||
|
/* Begin PBXBuildFile section */
|
||||||
|
8650B71D3075C74D00684CC4 /* SwiftAudioEx in Frameworks */ = {isa = PBXBuildFile; productRef = B10000013075A0CA00684CC4 /* SwiftAudioEx */; };
|
||||||
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
/* Begin PBXFileReference section */
|
||||||
8650B6A43075A0C900684CC4 /* Music.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Music.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
8650B6A43075A0C900684CC4 /* Music.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Music.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
@@ -23,6 +27,7 @@
|
|||||||
isa = PBXFrameworksBuildPhase;
|
isa = PBXFrameworksBuildPhase;
|
||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
|
8650B71D3075C74D00684CC4 /* SwiftAudioEx in Frameworks */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
@@ -65,6 +70,7 @@
|
|||||||
);
|
);
|
||||||
name = Music;
|
name = Music;
|
||||||
packageProductDependencies = (
|
packageProductDependencies = (
|
||||||
|
B10000013075A0CA00684CC4 /* SwiftAudioEx */,
|
||||||
);
|
);
|
||||||
productName = Music;
|
productName = Music;
|
||||||
productReference = 8650B6A43075A0C900684CC4 /* Music.app */;
|
productReference = 8650B6A43075A0C900684CC4 /* Music.app */;
|
||||||
@@ -94,6 +100,9 @@
|
|||||||
);
|
);
|
||||||
mainGroup = 8650B69B3075A0C900684CC4;
|
mainGroup = 8650B69B3075A0C900684CC4;
|
||||||
minimizedProjectReferenceProxies = 1;
|
minimizedProjectReferenceProxies = 1;
|
||||||
|
packageReferences = (
|
||||||
|
8650B7433075C7AB00684CC4 /* XCRemoteSwiftPackageReference "SwiftAudioEx" */,
|
||||||
|
);
|
||||||
preferredProjectObjectVersion = 77;
|
preferredProjectObjectVersion = 77;
|
||||||
productRefGroup = 8650B6A53075A0C900684CC4 /* Products */;
|
productRefGroup = 8650B6A53075A0C900684CC4 /* Products */;
|
||||||
projectDirPath = "";
|
projectDirPath = "";
|
||||||
@@ -253,7 +262,8 @@
|
|||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
ENABLE_USER_SELECTED_FILES = readonly;
|
ENABLE_USER_SELECTED_FILES = readonly;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = NO;
|
||||||
|
INFOPLIST_FILE = Info.plist;
|
||||||
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
|
||||||
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
|
||||||
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
|
||||||
@@ -298,7 +308,8 @@
|
|||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
ENABLE_USER_SELECTED_FILES = readonly;
|
ENABLE_USER_SELECTED_FILES = readonly;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = NO;
|
||||||
|
INFOPLIST_FILE = Info.plist;
|
||||||
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
|
||||||
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
|
||||||
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
|
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
|
||||||
@@ -353,6 +364,25 @@
|
|||||||
defaultConfigurationName = Release;
|
defaultConfigurationName = Release;
|
||||||
};
|
};
|
||||||
/* End XCConfigurationList section */
|
/* End XCConfigurationList section */
|
||||||
|
|
||||||
|
/* Begin XCRemoteSwiftPackageReference section */
|
||||||
|
8650B7433075C7AB00684CC4 /* XCRemoteSwiftPackageReference "SwiftAudioEx" */ = {
|
||||||
|
isa = XCRemoteSwiftPackageReference;
|
||||||
|
repositoryURL = "https://github.com/doublesymmetry/SwiftAudioEx.git";
|
||||||
|
requirement = {
|
||||||
|
kind = upToNextMajorVersion;
|
||||||
|
minimumVersion = 1.1.0;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/* End XCRemoteSwiftPackageReference section */
|
||||||
|
|
||||||
|
/* Begin XCSwiftPackageProductDependency section */
|
||||||
|
B10000013075A0CA00684CC4 /* SwiftAudioEx */ = {
|
||||||
|
isa = XCSwiftPackageProductDependency;
|
||||||
|
package = 8650B7433075C7AB00684CC4 /* XCRemoteSwiftPackageReference "SwiftAudioEx" */;
|
||||||
|
productName = SwiftAudioEx;
|
||||||
|
};
|
||||||
|
/* End XCSwiftPackageProductDependency section */
|
||||||
};
|
};
|
||||||
rootObject = 8650B69C3075A0C900684CC4 /* Project object */;
|
rootObject = 8650B69C3075A0C900684CC4 /* Project object */;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"originHash" : "fd663194cc3302df64b216b4569138f87e2a0bb4749a2439d12d0f6887e8ca1f",
|
||||||
|
"pins" : [
|
||||||
|
{
|
||||||
|
"identity" : "swiftaudioex",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/doublesymmetry/SwiftAudioEx.git",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "7b506bebabd68b542256c0e1e55519fab5f4c092",
|
||||||
|
"version" : "1.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version" : 3
|
||||||
|
}
|
||||||
@@ -9,9 +9,12 @@ import SwiftUI
|
|||||||
|
|
||||||
@main
|
@main
|
||||||
struct MusicApp: App {
|
struct MusicApp: App {
|
||||||
|
@StateObject private var player = PlayerManager()
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup {
|
WindowGroup {
|
||||||
ContentView()
|
ContentView()
|
||||||
|
.environmentObject(player)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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