Please Update Andorid MusicKit,the version 1.1.2 will complied fail。the error msg:•SDKUriHandlerActivity>. Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corres
Apple Music API
RSS for tagApple Music API integrates streaming music with Apple Music content.
Posts under Apple Music API tag
70 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have 2017 GMC Sierra and no bluetooth so I have to use USB. It worked fine for years but as soon as I down loaded the iOS 18 update when I try to listen to music, it plays a small clip of the song then stops and forwards through the rest of the song and skips to the next. It does this with every song whether it’s a playlist or downloaded on to my phone. I hate listening to the radio and having to listen to commercials which is why I have a 1 year subscription to Apple Music. Because of this glitch I have to listen to the friggin radio in the truck and search for the radio stations I like and suffer through stupid commercials every 10 minutes. None of the updates have fixed this glitch. Please, I beg you, fix it.
I have tried everything. The songs load unto the playlists and on searches, but when prompted to play, they just won't play.
I have a wrapper since my main player (which carries the buttons for play/rewind/forward/etc.), is in Objc.
//
// ApplePlayerWrapper.swift
// UniversallyMac
//
// Created by Dorian Mattar on 11/10/24.
//
import Foundation
import MusicKit
import MediaPlayer
@objc public class MusicKitWrapper: NSObject {
@objc public static let shared = MusicKitWrapper()
private let player = ApplicationMusicPlayer.shared
// Play the current track
@objc public func play() {
guard !player.queue.entries.isEmpty else {
print("Queue is empty. Cannot start playback.")
return
}
logPlayerState(message: "Before play")
Task {
do {
try await player.prepareToPlay()
try await player.play()
print("Playback started successfully.")
} catch {
if let nsError = error as NSError? {
print("NSError Code: \(nsError.code), Domain: \(nsError.domain)")
}
}
logPlayerState(message: "After play")
}
}
// Log the current player state
@objc public func logPlayerState(message: String = "") {
print("Player State - \(message):")
print("Playback Status: \(player.state.playbackStatus)")
print("Queue Count: \(player.queue.entries.count)")
// Only log current track details if the player is playing
if player.state.playbackStatus == .playing {
if let currentEntry = player.queue.currentEntry {
print("Current Track: \(currentEntry.title)")
print("Current Position: \(player.playbackTime) seconds")
print("Track Length: \(currentEntry.endTime ?? 0.0) seconds")
} else {
print("No current track.")
}
} else {
print("No track is playing.")
}
print("----------")
}
// Debug the queue
@objc public func debugQueue() {
print("Debugging Queue:")
for (index, entry) in player.queue.entries.enumerated() {
print("\(index): \(entry.title)")
}
}
// Ensure track availability in the queue
public func queueTracks(_ tracks: [Track]) {
Task {
do {
for track in tracks {
// Validate Play Parameters
guard let playParameters = track.playParameters else {
print("Track \(track.title) has no Play Parameters.")
continue
}
// Log the Play Parameters
print("Track Title: \(track.title)")
print("Play Parameters: \(playParameters)")
print("Raw Values: \(track.id.rawValue)")
// Ensure the ID is valid
if track.id.rawValue.isEmpty {
print("Track \(track.title) has an invalid or empty ID in Play Parameters.")
continue
}
// Queue the track
try await player.queue.insert(track, position: .afterCurrentEntry)
print("Queued track: \(track.title)")
}
print("Tracks successfully added to the queue.")
} catch {
print("Error queuing tracks: \(error)")
}
debugQueue()
}
}
// Clear the current queue
@objc public func resetMusicPlayer() {
Task {
player.stop()
player.queue.entries.removeAll()
print("Queue cleared.")
print("Apple Music player reset successfully.")
}
}
}
I opened an Apple Dev. ticket, but I'm trying here as well. Thanks!
I'm unable to play music using Musickit.js in the Chrome or Firefox browsers.
Even using the apple guide here: https://js-cdn.music.apple.com/musickit/v1/index.html - I've added my Music Developer Token and song/album url, but it only works in Safari and not in Chrome or Firefox.
I'm unsure if this is a global issue, or if there is something I need to do to enable playback in other browsers, but as it stands it's not working for me.
Thanks for any help in advance!
Hi,
I have been working on a project that enables users to listen to their favorite music using a streaming service, which so far was Spotify. The app had a programmable 3D/2D interface with the ability to connect to devices in your home and have them react to music. As of September 2024, Spotify decomissioned their Audio Analysis API. I have seen other posts mention playing Apple Music through AVFoundation, which would break DRM and so it’s not supported. However, the Spotify Audio Analysis API does not allow for a full frequency reconstruction. It is entirely temporal data on beats, kicks, loudness, and timbre changes, which themselves are operators on the spectral data from the FFT. It would be very useful for the developer community if we get the ability to do this and it will probably Apple Music among developers and those who use their apps a lot more.
Would love to hear your thoughts about this and Happy New Year!
I'm trying to load Music Kit on the server with solid js. I can confirm that my implementation has been sufficient to return authentication tokens and for MusicKit.isAuthorized to return true. My issue is that if I reload the page, it only succeeds intermittently (perhaps 25% of the time?). My question is - what is wrong with my implementation? Removing the async keyword ensures it loads every time but playing and queuing music no longer works. I'm currently assuming this is an SSR issue but the docs haven't explicitly specified this isn't possible.
I have the following boilerplate:
export default createHandler(
() => (
<StartServer
document={({ assets, children, scripts }) => {
return (
<html lang="en">
<head>
<meta name="apple-music-developer-token" content={authResult.token} />
<meta name="apple-music-app-name" content="app name" />
<meta name="apple-music-app-build" content="1978.4.1" />
{assets}
<script
src="https://js-cdn.music.apple.com/musickit/v3/musickit.js"
async
/>
</head>
<body>
<div id="app">{children}</div>
{scripts}
</body>
</html>
)
}}
/>
))
When I first load my app, I'll encounter:
musickit.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'node')
at musickit.js:13:10194
at musickit.js:13:140
at musickit.js:13:209
The intermittence signals an issue relating to the async keyword. An expansion on this issue can be found here.
Hi All,
I am working on a DJ playout app (MACOS). The app has a few AVAudioPlayerNode's combined with the ApplicationMusicPlayer from Musickit. I can route the output of the AVaudioPlayer to a hardware device so that the audio files are directed to their own dedicated output on my Mac. The ApplicationMusicPlayer is following the default output and this is pretty annoying.
Has anyone found a solution to chain the ApplicationMusicPlayer and get it set to a output device?
Thanks
Pancras
Hello,
I am having difficulties with configuring MusicKit correctly for my web app that I am building, seeking assistance with the issues I am having. Would greatly appreciate any help!
After allowing access to the following,
"Access Request
media.mydomain.com would like to access Apple Music, media library, and listening activity for myemail'@icloud.com.",
I get a popup error that states, "Authorization failed. Please try again.".
Following is the information that is given in developer console:
[Error] Failed to load resource: the server responded with a status of 403 () (webPlayerLogout, line 0)
[Error] Authorization failed:
AUTHORIZATION_ERROR: Unauthorized
(anonymous function) (media.mydomain.com:398)
We use BassDSDPlayer / SFBAudioEngine to play just about any file, but playing Apple Music is failing. All subscriptions are up to date. We stop the SFBAudioEngine and the BassDSDPlayer before playing Apple Music to no avail.
PRINTS:
Supported files in /Users/dorian/Music/Music/Media.localized/Music/4: 28364
Apple Music is authorized and can play catalog.
Resetting default output device...
Releasing BassDSDPlayer audio device...
BassDSDPlayer: Audio device released.
STOPPED sfbAudioDevice
Default output device is ID: 76
applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong]
applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong]
Player State - After resetting output:
Playback Status: stopped
Queue Count: 0
No track is playing.
Music player reset successfully.
BassDSDPlayer: Audio device released.
Default output device set successfully: 76
Default output device is ID: 76
Default output device set successfully: 76
Default output device ID: 76
Validated PlayParameters for track: squabble up
PlayParameters: PlayParameters(id: 1781270321, kind: "song", isLibrary: nil, catalogID: nil, libraryID: nil, deviceLocalID: nil, rawValues: [:])
Starting playback...
Player State - After playback:
Playback Status: stopped
Queue Count: 1
No track is playing.
Notification BASS DSD NSConcreteNotification 0x600007ce2b00 {name = kUpdateSongInfo; object = {
AlbumTitle = GNX;
ArtistName = "Kendrick Lamar";
SongArtwork = "<NSImage 0x6000041b7ca0 Size={300, 300} RepProvider=<NSImageArrayRepProvider: 0x600003518770, reps:(\n "NSBitmapImageRep 0x600009ed9dc0 Size={300, 300} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=300x300 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600007ce15c0"\n)>>";
SongLength = "157.992";
SongTitle = "squabble up";
Source = AppleMusic;
}}
Apple Music track loaded: squabble up by Kendrick Lamar
Player State - Before play:
Playback Status: stopped
Queue Count: 1
No track is playing.
prepareToPlay failed [no target descriptor]
NSError Code: 1, Domain: MPMusicPlayerControllerErrorDomain
Player State - After play:
Playback Status: stopped
Queue Count: 1
No track is playing.
func playAppleMusicTracks(tracks: [Track]) {
AppleMusicManager.shared.isAuthorizedAndReadyForPlayback { isAuthorized in
guard isAuthorized else {
print("Apple Music authorization or capabilities insufficient for playback.")
return
}
print("Resetting default output device...")
self.stopSFBAudioDevice()
self.resetMusicPlayer()
self.resetAudioSystem()
self.ensureOutputDeviceReady()
Task {
for track in tracks {
guard self.validatePlayParameters(for: track) else { continue }
do {
try await ApplicationMusicPlayer.shared.queue.insert(track, position: .afterCurrentEntry)
guard !ApplicationMusicPlayer.shared.queue.entries.isEmpty else {
print("Queue is empty after queuing. Playback cannot proceed.")
return
}
self.notifyAppleMusicTrackInfo(track)
} catch {
print("Error starting playback: \(error)")
if let nsError = error as NSError? {
print("NSError Code: \(nsError.code), Domain: \(nsError.domain)")
}
}
}
MusicKitWrapper.shared.logPlayerState(message: "After playback")
}
}
}
@objc public class MusicKitWrapper: NSObject {
@objc public static let shared = MusicKitWrapper()
private let player = ApplicationMusicPlayer.shared
// Play the current track
@objc public func play() {
guard !player.queue.entries.isEmpty else {
print("Queue is empty. Cannot start playback.")
return
}
logPlayerState(message: "Before play")
Task {
do {
try await player.prepareToPlay()
try await player.play()
print("Playback started successfully.")
} catch {
if let nsError = error as NSError? {
print("NSError Code: \(nsError.code), Domain: \(nsError.domain)")
}
}
logPlayerState(message: "After play")
}
}
Any help would be appreciated.
Thanks!
Hi! Im attempting to make a spotify to apple playlist converter and to do so am using the Catalog search functionality of the api. My question is, is there anyway to convert these songs to apple music urls (or ids) that does not spam api calls. I know you can batch catalog searches if you have apple music song ids, but I obviously dont have that since the song was shared from spotify. Any ideas/help is appreciated!
Hello,
I have a question related to the public iTunes Search API: https://performance-partners.apple.com/search-api
Do all the books have an ISBN associated? I used to do queries like:
https://itunes.apple.com/lookup?isbn=9781501110368. That book is available on Apple Books here: https://books.apple.com/us/book/it-ends-with-us/id1052928247 and the endpoint above returns informations about it.
However for newer books like:
https://itunes.apple.com/lookup?isbn=9781419766954
https://itunes.apple.com/lookup?isbn=9781250288776
Nothing comes back anymore even if those books exist there. The url's for the 2 above are:
https://books.apple.com/us/book/hot-mess-diary-of-a-wimpy-kid-19/id6476554491
https://books.apple.com/mt/book/the-mirror/id6474420363
For newer books starting the beginning of September 2024, nothing seems to come back when you search them by ISBN.
Thanks
Hello,
This is about the Get Catalog Top Charts Genres endpoint :
GET https://api.music.apple.com/v1/catalog/{storefront}/genres
I noticed that for some storefronts, no genre is returned. You can try with the following storefront values :
France (fr)
Poland (pl)
Kyrgyzstan (kg)
Uzbekistan (uz)
Turkmenistan (tm)
Is that a bug or is it on purpose ?
Thank you.
I'm developing a Raycast extension that using Apple MusicKit API, is it safe to store developer tokens in Raycast extensions?
I'm trying (in Swift) to use CryptoKit to generate the required JWT for the Apple Music Web API, as documented (sort of) here.
But I'm getting 401s no matter what I try. I found some examples of generating JWTs online, but something isn't working here. I've set up my identifiers and gotten an API secret through my account in the dev portal. It's associated with an identifier requesting Music API access (I requested all three available Music-related capabilities).
For the secret, I'm using the long key string from the .p8 file I generated and downloaded from the dev portal.
Here's what I've tried:
struct APIToken
{
struct Header: Encodable
{
let alg = "HS256"
let kid: String
}
struct Payload: Encodable
{
let iss: String
let iat: String
let exp: String
}
static func tokenize(keyID: String, issuerID: String, secret: String) -> String
{
let privateKey = SymmetricKey(data: Data(secret.utf8))
let headerJSONData = try! JSONEncoder().encode(Header(kid: keyID))
let headerBase64String = headerJSONData.base64EncodedString()
let currUnixTime = Int(Date().timeIntervalSince1970)
let expUnixTime = currUnixTime + 5 * 2628288 // five months of seconds
let payloadJSONData = try! JSONEncoder().encode(Payload(iss: issuerID, iat: "\(currUnixTime)", exp: "\(expUnixTime)"))
let payloadBase64String = payloadJSONData.base64EncodedString()
let toSign = Data((headerBase64String + "." + payloadBase64String).utf8)
let signature = HMAC<SHA256>.authenticationCode(for: toSign, using: privateKey)
let signatureBase64String = Data(signature).base64EncodedString()
let token = [headerBase64String, payloadBase64String, signatureBase64String].joined(separator: ".")
print(token)
return token
}
}
I also tried making sure the base64 strings are URL-safe with this extension:
extension Data
{
func URLSafeBase64EncodedString() -> String
{
return base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
but that made no difference.
All the documentation says is
A decoded developer token has the following format.
{
"alg": "ES256",
"kid": "ABC123DEFG"
}
{
"iss": "DEF123GHIJ",
"iat": 1437179036,
"exp": 1493298100
}
After you create the token, sign it with your MusicKit private key using the ES256 algorithm.
Am I not doing that? Any insight appreciated.
How to capture the audio being played by apple music in ios and combine it with fft to achieve audio visualization?
I am building an app for MacOS and I am trying to implement the code to add songs to a library playlist (which is added below). The issue I am having is that if I use Music Kit to load a users library playlists, the ID for the playlist (which is just a string of numbers) does not work with the Add tracks to a Library Playlist endpoint of Apple Music API. If I retrieve the playlists from the Apple Music API and use that playlist ID (which is different than the id I get from MusicKit) my code works fine and adds the song to the playlist. The problem is that when getting a users library playlists from Apple Music API is that it does not give me all of the library playlists that I get when using Music Kit and it also does not give me Artwork for playlists that have the collage of album covers, so I would prefer to use Music Kit to get the playlists.
I have also tested trying to retrieve a single playlist using the Apple Music API with the playlist Id from Music Kit and it does not work. I get the error that the resource cannot be found. Since this is a macOs app I cannot use MusicKit to add songs to library playlists.
Does anyone know a way to resolve this? Or a possible workaround? Ideally I want to use MusicKit to get the library playlists and have some way to use the playlist Id and add songs to that playlist. Below is my code for adding a song to a playlist using the Apple Music API, which works correctly only if I originally get the library playlist's id value from a playlist retrieved from the Apple Music API.
Also, does anyone know why the playlist Id's are not universal and are different when using Music Kit and Apple Music API? For songs and tracks it does not seem to matter if I use music kit or Apple Music API, the Id's are in the correct format for Apple Music API to use and work with my code. Thanks everyone for any and all help!
func addToPlaylist(songs: [Track], playlist: Playlist, alert: Binding<AlertItem?>) async {
let tracks = AppleMusicPlaylistPostRequestBody(data: songs.compactMap {
AppleMusicPlaylistPostRequestItem(id: $0.id.rawValue, type: "songs") // or "library-songs"
})
let playlistID = playlist.id
// Build the request URL for adding a song to a playlist
guard let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists/\(playlistID)/tracks") else {
alert.wrappedValue = AlertItem(title: "Error", message: "Invalid URL for the playlist.")
return
}
// Authorization Header
guard let musicUserToken = try? await MusicUserTokenProvider().getUserMusicToken() else {
alert.wrappedValue = AlertItem(title: "Error", message: "Unable to retrieve Music User Token.")
return
}
do {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(musicUserToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let encoder = JSONEncoder()
let data = try encoder.encode(tracks)
request.httpBody = data
let musicRequest = MusicDataRequest(urlRequest: request)
let musicRequestResponse = try await musicRequest.response()
// Check if the request was successful (status 201)
if musicRequestResponse.urlResponse.statusCode == 201 {
alert.wrappedValue = AlertItem(title: "Success", message: "Song successfully added to the playlist.")
} else {
print("Status Code: \(musicRequestResponse.urlResponse.statusCode)")
print("Response Data: \(String(data: musicRequestResponse.data, encoding: .utf8) ?? "No Data")")
// Attempt to decode the error response into the AppleMusicErrorResponse model
if let appleMusicError = try? JSONDecoder().decode(AppleMusicErrorResponse.self, from: musicRequestResponse.data) {
let errorMessage = appleMusicError.errors.first?.detail ?? "Unknown error occurred."
alert.wrappedValue = AlertItem(title: "Error", message: errorMessage)
} else {
alert.wrappedValue = AlertItem(title: "Error", message: "Failed to add song to the playlist.")
}
}
} catch {
alert.wrappedValue = AlertItem(title: "Error", message: "Network error: \(error.localizedDescription)")
}
}
https://developer.apple.com/documentation/WidgetKit/Adding-interactivity-to-widgets-and-Live-Activities#Add-a-toggle
Before explaining the situation, I referred to this document.
I'm making a widget with a toggle that works with Intent. (To be precise, it's Live Activity, but Apple's literally toggling and button interaction are implemented in the same way)
If you press the toggle when the device is locked, the toggle represents the state.
However, as described at the top of the same document, the device must be unlocked to execute Intent, so I can't actually change the data.
That's fine, but how can I return the isOn of the toggle to false? I'm blocked here because no code is executed.
If it is a widget in the home screen, it will be basically unlocked, so I can proceed according to the method of the document, but if it is today's view, user can access it even if device is locked.
I tested it in today's view with the Reminders app, If I don't unlock the device after tapping the toggle it returns the toggle back to false state.
I wonder how I can achieve this.
Is there an API that I missed?
Summary.
Tap the toggle of the widget while the device is locked.
The device waits for unlocking, but the user cancels it without unlocking it. (Still locked)
Return the isOn of the toggle to false. <- The part I want.
Hi all, I am working with MusicKit and have managed to get a user's recommendation playlists (favorites, get up, etc). Isolating just one, I am trying to access the tracks in there using .tracks but it returns nothing. Wondering if I am doing something wrong or if these don't have tracks necessarily associated with them.
Code is below
(not everything just kinda where I am accessing the playlist)
try await requestMusicAuthorization()
let request = MusicPersonalRecommendationsRequest()
let response = try await request.response()
guard let madeForYou = response.recommendations.first(where: { $0.title == "Made for You" }) else {
throw NSError(domain: "RecommendationError", code: 0, userInfo: [NSLocalizedDescriptionKey: "No 'Made for You' recommendation found."])
}
guard let firstPlaylist = madeForYou.playlists.first else {
throw NSError(domain: "PlaylistError", code: 1, userInfo: [NSLocalizedDescriptionKey: "No playlists found in 'Made for You' recommendation."])
}
print("Fetching tracks for playlist: \(firstPlaylist.name ?? "Unknown")")
let playlistRequest = MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: firstPlaylist.id)
let playlistResponse = try await playlistRequest.response()
guard let playlist = playlistResponse.items.first else {
throw NSError(domain: "PlaylistError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Couldn't fetch the playlist details."])
}
guard let tracks = playlist.tracks else {
throw NSError(domain: "PlaylistError", code: 3, userInfo: [NSLocalizedDescriptionKey: "No tracks found in the playlist."])
}
Hi, I've recently been working with the Apple Music API and have had success in loading all the playlists on my account, loading songs from each playlist, and adding songs to the ApplicationMusicPlayer.share.queue. The problem I'm running into is that not all songs from the playlist are being added to the queue, despite confirming all the songs are being based on the PlaybackView.swift I'm about to share with you. I would also like to answer other underlying questions if possible. I am also open to any other suggestions. In this scenario were also assuming isShuffled is true every time.
How can I determine when a song has ended?
How can I get the album title information?
How can I get the current song title, album information, and artist information without pressing play? I can only seem to update the screen when I select my play meaning ApplicationMusicPlayer.shared.play() is being called.
How do I get the endTime of the song? I believe it should be ApplicationMusicPlayer.shared.queue.currentEntry.endTime but this doesn't seem to work.
//
// PlayBackView.swift
//
// Created by Justin on 8/16/24.
//
import SwiftUI
import MusicKit
import Foundation
enum PlayState {
case play
case pause
}
struct PlayBackView: View {
@State var song: Track
@Binding var songs: [Track]?
@State var isShuffled = false
@State private var playState: PlayState = .pause
@State private var isFirstPlay = true
private let player = ApplicationMusicPlayer.shared
private var isPlaying: Bool {
return (player.state.playbackStatus == .playing)
}
var body: some View {
VStack {
// Album Cover
HStack(spacing: 20) {
if let artwork = player.queue.currentEntry?.artwork {
ArtworkImage(artwork, height: 100)
} else {
Image(systemName: "music.note")
.resizable()
.frame(width: 100, height: 100)
}
VStack(alignment: .leading) {
// Song Title
Text(player.queue.currentEntry?.title ?? "Song Title Not Found")
.font(.title)
.fixedSize(horizontal: false, vertical: true)
// How do I get AlbumTitle from here??
// Artist Name
Text(player.queue.currentEntry?.subtitle ?? "Artist Name Not Found")
.font(.caption)
}
}
.padding()
Spacer()
// Progress View
// endTime doesn't work and not sure why.
ProgressView(value: player.playbackTime, total: player.queue.currentEntry?.endTime ?? 1.00)
.progressViewStyle(.linear)
.tint(.red.opacity(0.5))
// Duration View
HStack {
Text(durationStr(from: player.playbackTime))
.font(.caption)
Spacer()
if let duration = player.queue.currentEntry?.endTime {
Text(durationStr(from: duration))
.font(.caption)
}
}
Spacer()
Button {
Task {
do {
try await player.skipToNextEntry()
} catch {
print(error.localizedDescription)
}
}
} label: {
Label("", systemImage: "forward.fill")
.tint(.white)
}
Spacer()
// Play/Pause Button
Button(action: {
handlePlayButton()
isFirstPlay = false
}, label: {
Text(playState == .play ? "Pause" : isFirstPlay ? "Play" : "Resume")
.frame(maxWidth: .infinity)
})
.buttonStyle(.borderedProminent)
.padding()
.font(.largeTitle)
.tint(.red)
}
.padding()
.onAppear {
if isShuffled {
songs = songs?.shuffled()
if let songs, let firstSong = songs.first {
player.queue = .init(for: songs, startingAt: firstSong)
player.state.shuffleMode = .songs
}
}
}
.onDisappear {
player.stop()
player.queue = []
player.playbackTime = .zero
}
}
private func handlePlayButton() {
Task {
if isPlaying {
player.pause()
playState = .pause
} else {
playState = .play
await playTrack()
}
}
}
@MainActor
private func playTrack() async {
do {
try await player.play()
} catch {
print(error.localizedDescription)
}
}
private func durationStr(from duration: TimeInterval) -> String {
let seconds = Int(duration)
let minutes = seconds / 60
let remainder = seconds % 60
// Format the string to ensure two digits for the remainder (seconds)
return String(format: "%d:%02d", minutes, remainder)
}
}
//#Preview {
// PlayBackView()
//}
Since the iOS 18 update, there's been a bug that always occurs when listening to music through Apple Music. When music is playing and the iPhone enters or exits standby mode, the music pauses by itself for 1 second. The initial conditions were the same as when this problem didn’t exist.