Post

Replies

Boosts

Views

Activity

Playlist IDs from MusicKit not working with Apple Music API
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)") } }
1
1
1.2k
Dec ’24
Help with showing a spectrogram of an audio file
Hello everyone! I am trying to create a spectrogram like in the attached image for a macOs App. I am using Cocoa/AppKit but also have some SwiftUI views, so I can use either. I have found the sample app Visualizing Sound as an Audio Spectogram that apple provides but I do not want a real-time spectrogram. I want a spectrogram of the whole audio file. I have been trying to convert the sample app to what I need but I have been unsuccessful so far. Here is how I changed the code in the delegate public func captureBuffer() { let asset = AVAsset(url: audioFileUrl) let reader = try! AVAssetReader(asset: asset) let track = asset.tracks(withMediaType: AVMediaType.audio)[0] let settings = [ AVFormatIDKey : kAudioFormatLinearPCM ] let readerOutput = AVAssetReaderTrackOutput(track: track, outputSettings: settings) reader.add(readerOutput) reader.startReading() while let buffer = readerOutput.copyNextSampleBuffer() {   var audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))   var blockBuffer: CMBlockBuffer?   CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer( buffer, bufferListSizeNeededOut: nil, bufferListOut: &audioBufferList, bufferListSize:  MemoryLayout<AudioBufferList>.size, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &blockBuffer   ); let buffers = UnsafeBufferPointer<AudioBuffer>(start: &audioBufferList.mBuffers, count: Int(audioBufferList.mNumberBuffers)) for buffer in buffers { let samplesCount = Int(buffer.mDataByteSize) / MemoryLayout<Int16>.size let samplesPointer = audioBufferList.mBuffers.mData!.bindMemory(to: Int16.self, capacity: samplesCount) let samples = UnsafeMutableBufferPointer<Int16>(start: samplesPointer, count: samplesCount) } guard let data = audioBufferList.mBuffers.mData else { return } /// The _Nyquist frequency_ is the highest frequency that a sampled system can properly /// reproduce and is half the sampling rate of such a system. Although  this app doesn't use /// `nyquistFrequency` you may find this code useful to add an overlay to the user interface. if nyquistFrequency == nil { let duration = Float(CMSampleBufferGetDuration(buffer).value) let timescale = Float(CMSampleBufferGetDuration(buffer).timescale) let numsamples = Float(CMSampleBufferGetNumSamples(buffer)) nyquistFrequency = 0.5 / (duration / timescale / numsamples) } if self.rawAudioData.count < AudioSpectrogram.sampleCount * 2 { let actualSampleCount = CMSampleBufferGetNumSamples(buffer) let ptr = data.bindMemory(to: Int16.self, capacity: actualSampleCount) let buf = UnsafeBufferPointer(start: ptr, count: actualSampleCount) rawAudioData.append(contentsOf: Array(buf)) } while self.rawAudioData.count >= AudioSpectrogram.sampleCount { let dataToProcess = Array(self.rawAudioData[0 ..< AudioSpectrogram.sampleCount]) self.rawAudioData.removeFirst(AudioSpectrogram.hopCount) self.processData(values: dataToProcess) } createAudioSpectrogram() } } } I am sure there are different or better ways to go about this, but the only examples I can find are on iOS and use UIKit, but I am building for MacOs. Does anyone know how display a spectrogram for an audio file without having to play the audio file? I dont mind using sox or ffmpeg if that is easier. Greatly appreciated!
2
0
2k
Oct ’22
This Mac can’t connect to Apple Media Services because of a problem with "my Apple ID email address"
I am using Xcode 13.2 on MacOS 12.2. I have been building and running my app in Xcode for months with no issues. I stopped working on it for a couple of days while out of town. The next time I ran my app, I get this pop-up warning saying "This Mac can’t connect to Apple Media Services because of a problem with "my Apple ID email address" when the app uses MusicKit to search for an album. When I push "Apple ID Preferences...", it takes me there and another pop-up asks me to "sign in to Media Services using my Apple ID", even though I am already signed in. Once I sign in, my app continues to run. If I hit the "Later" button, the pop-up goes away and my app continues to run just fine. My computer was off when I was out of town, so no one did anything to it and no auto-updates were performed or anything. I tried signing out of iCloud, Apple Music... etc, restarting and signing back into everything as suggested by Apple customer service but that did not help. They say everything is fine with my Apple ID so it is an issue with Xcode. This happens every time I run my app in Xcode. Does anyone have any idea what is going on? Please help. Much appreciated!
3
0
2.3k
Jun ’22
How to get the output of a for-in loop into a single DataFrame instead of many Dataframes
I am trying to get the data for each track in a MusicItemCollection into a DataFrame. The only way I know to go about this is to use a for-in loop, but this creates a DataFrame for each track instead of a DataFrame for all of the tracks. My code is: let albumTracks = album?.tracks for tracks in albumTracks {      let dataFrame: DataFrame = [          "track": [tracks.trackNumber],          "title": [tracks.title],          "artist": [tracks.artistName],          "release date": [tracks.releaseDate?.formatted(date: .long, time: .omitted) ?? "not available"],          "duration": [tracks.duration],          "isrc": [tracks.isrc]          ]      print(dataFrame) I have also tried  for tracks in self.albumTracks {      var dataFrame = DataFrame.init()      let trackNumColumn = Column.init(name: "track", contents: [String(tracks.trackNumber!)])      dataFrame.append(column: trackNumColumn)      let titleColumn = Column.init(name: "title", contents: [tracks.title])      dataFrame.append(column: titleColumn)      let artistColumn = Column.init(name: "artist", contents: [tracks.artistName])      dataFrame.append(column: artistColumn)      let releaseDateColumn = Column.init(name: "release date", contents: [tracks.releaseDate?.formatted(date: .long, time: .omitted)])      dataFrame.append(column: releaseDateColumn)      let idColumn = Column.init(name: "id", contents: [String(tracks.id.rawValue)])      dataFrame.append(column: idColumn)            print(dataFrame) Both of these methods work outside of a loop according to the tech talks video: https://developer.apple.com/videos/play/tech-talks/10100/ , but I cannot figure out how to call the individual tracks outside of a loop Thanks
4
0
2.0k
Jan ’22
SwiftUI Mac OS toolbar at top of sheet window?
Hi, From a navigation view, I open a sheet view (instead of having a 3-column view). While I can make a toolbar, it only shows at the bottom of the window. Does anyone know how to get the toolbar at the top of the window, if it is even possible? Or is the toolbar only allowed at the bottom of the window in a sheet view? Thanks!
3
0
1.6k
Jan ’22
Having trouble getting MusicKit Data into my SwiftUI view
Having trouble getting the data from MusicKit Searches back to my SwiftUI view. Normally I would use a @State variable for the decodable structure, but with MusicKit you dont need to decode anything and I can't figure out how to best get the data back to my view. I call the MusicKit function using .onAppear in my SwiftUI view func getAlbum() async throws -> MusicItemCollection<Album> {         var request = MusicCatalogResourceRequest<Album>(matching: \.id, equalTo: "1440881121")         let response = try await request.response()         print(response.debugDescription)         return response.items        printing debugDescription give these results: MusicCatalogResourceResponse<Album>(   items: [     Album(       id: "1440881121",       title: "Colors",       artistName: "Beck",       contentRating: "explicit",       copyright: Fonograf Records/Capitol Records; ℗ 2017 Fonograf Records, under exclusive license to UMG Recordings, Inc.,       genreNames: [         "Alternative",         "Music"       ],       isCompilation: false,       isComplete: true,       isDigitalMaster: true,       isSingle: false,       releaseDate: "2017-10-13",       trackCount: 11,       upc: "00602557176827" Hoe would you access all of the data in the debugDescription and use it in your SwiftUI view? I can only access the standard name and id. Is anyone using Codable to move the data through a data model? The documentation is not making sense to me even though I am usually ok using it. Also, should I be using `func getAlbum() async throws -> MusicCatalogResourceResponse {' instead of using MusicItemCollection? Thanks
8
0
2.7k
Jan ’22
Playlist IDs from MusicKit not working with Apple Music API
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)") } }
Replies
1
Boosts
1
Views
1.2k
Activity
Dec ’24
Help with showing a spectrogram of an audio file
Hello everyone! I am trying to create a spectrogram like in the attached image for a macOs App. I am using Cocoa/AppKit but also have some SwiftUI views, so I can use either. I have found the sample app Visualizing Sound as an Audio Spectogram that apple provides but I do not want a real-time spectrogram. I want a spectrogram of the whole audio file. I have been trying to convert the sample app to what I need but I have been unsuccessful so far. Here is how I changed the code in the delegate public func captureBuffer() { let asset = AVAsset(url: audioFileUrl) let reader = try! AVAssetReader(asset: asset) let track = asset.tracks(withMediaType: AVMediaType.audio)[0] let settings = [ AVFormatIDKey : kAudioFormatLinearPCM ] let readerOutput = AVAssetReaderTrackOutput(track: track, outputSettings: settings) reader.add(readerOutput) reader.startReading() while let buffer = readerOutput.copyNextSampleBuffer() {   var audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))   var blockBuffer: CMBlockBuffer?   CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer( buffer, bufferListSizeNeededOut: nil, bufferListOut: &audioBufferList, bufferListSize:  MemoryLayout<AudioBufferList>.size, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &blockBuffer   ); let buffers = UnsafeBufferPointer<AudioBuffer>(start: &audioBufferList.mBuffers, count: Int(audioBufferList.mNumberBuffers)) for buffer in buffers { let samplesCount = Int(buffer.mDataByteSize) / MemoryLayout<Int16>.size let samplesPointer = audioBufferList.mBuffers.mData!.bindMemory(to: Int16.self, capacity: samplesCount) let samples = UnsafeMutableBufferPointer<Int16>(start: samplesPointer, count: samplesCount) } guard let data = audioBufferList.mBuffers.mData else { return } /// The _Nyquist frequency_ is the highest frequency that a sampled system can properly /// reproduce and is half the sampling rate of such a system. Although  this app doesn't use /// `nyquistFrequency` you may find this code useful to add an overlay to the user interface. if nyquistFrequency == nil { let duration = Float(CMSampleBufferGetDuration(buffer).value) let timescale = Float(CMSampleBufferGetDuration(buffer).timescale) let numsamples = Float(CMSampleBufferGetNumSamples(buffer)) nyquistFrequency = 0.5 / (duration / timescale / numsamples) } if self.rawAudioData.count < AudioSpectrogram.sampleCount * 2 { let actualSampleCount = CMSampleBufferGetNumSamples(buffer) let ptr = data.bindMemory(to: Int16.self, capacity: actualSampleCount) let buf = UnsafeBufferPointer(start: ptr, count: actualSampleCount) rawAudioData.append(contentsOf: Array(buf)) } while self.rawAudioData.count >= AudioSpectrogram.sampleCount { let dataToProcess = Array(self.rawAudioData[0 ..< AudioSpectrogram.sampleCount]) self.rawAudioData.removeFirst(AudioSpectrogram.hopCount) self.processData(values: dataToProcess) } createAudioSpectrogram() } } } I am sure there are different or better ways to go about this, but the only examples I can find are on iOS and use UIKit, but I am building for MacOs. Does anyone know how display a spectrogram for an audio file without having to play the audio file? I dont mind using sox or ffmpeg if that is easier. Greatly appreciated!
Replies
2
Boosts
0
Views
2k
Activity
Oct ’22
This Mac can’t connect to Apple Media Services because of a problem with "my Apple ID email address"
I am using Xcode 13.2 on MacOS 12.2. I have been building and running my app in Xcode for months with no issues. I stopped working on it for a couple of days while out of town. The next time I ran my app, I get this pop-up warning saying "This Mac can’t connect to Apple Media Services because of a problem with "my Apple ID email address" when the app uses MusicKit to search for an album. When I push "Apple ID Preferences...", it takes me there and another pop-up asks me to "sign in to Media Services using my Apple ID", even though I am already signed in. Once I sign in, my app continues to run. If I hit the "Later" button, the pop-up goes away and my app continues to run just fine. My computer was off when I was out of town, so no one did anything to it and no auto-updates were performed or anything. I tried signing out of iCloud, Apple Music... etc, restarting and signing back into everything as suggested by Apple customer service but that did not help. They say everything is fine with my Apple ID so it is an issue with Xcode. This happens every time I run my app in Xcode. Does anyone have any idea what is going on? Please help. Much appreciated!
Replies
3
Boosts
0
Views
2.3k
Activity
Jun ’22
How to get the output of a for-in loop into a single DataFrame instead of many Dataframes
I am trying to get the data for each track in a MusicItemCollection into a DataFrame. The only way I know to go about this is to use a for-in loop, but this creates a DataFrame for each track instead of a DataFrame for all of the tracks. My code is: let albumTracks = album?.tracks for tracks in albumTracks {      let dataFrame: DataFrame = [          "track": [tracks.trackNumber],          "title": [tracks.title],          "artist": [tracks.artistName],          "release date": [tracks.releaseDate?.formatted(date: .long, time: .omitted) ?? "not available"],          "duration": [tracks.duration],          "isrc": [tracks.isrc]          ]      print(dataFrame) I have also tried  for tracks in self.albumTracks {      var dataFrame = DataFrame.init()      let trackNumColumn = Column.init(name: "track", contents: [String(tracks.trackNumber!)])      dataFrame.append(column: trackNumColumn)      let titleColumn = Column.init(name: "title", contents: [tracks.title])      dataFrame.append(column: titleColumn)      let artistColumn = Column.init(name: "artist", contents: [tracks.artistName])      dataFrame.append(column: artistColumn)      let releaseDateColumn = Column.init(name: "release date", contents: [tracks.releaseDate?.formatted(date: .long, time: .omitted)])      dataFrame.append(column: releaseDateColumn)      let idColumn = Column.init(name: "id", contents: [String(tracks.id.rawValue)])      dataFrame.append(column: idColumn)            print(dataFrame) Both of these methods work outside of a loop according to the tech talks video: https://developer.apple.com/videos/play/tech-talks/10100/ , but I cannot figure out how to call the individual tracks outside of a loop Thanks
Replies
4
Boosts
0
Views
2.0k
Activity
Jan ’22
SwiftUI Mac OS toolbar at top of sheet window?
Hi, From a navigation view, I open a sheet view (instead of having a 3-column view). While I can make a toolbar, it only shows at the bottom of the window. Does anyone know how to get the toolbar at the top of the window, if it is even possible? Or is the toolbar only allowed at the bottom of the window in a sheet view? Thanks!
Replies
3
Boosts
0
Views
1.6k
Activity
Jan ’22
Having trouble getting MusicKit Data into my SwiftUI view
Having trouble getting the data from MusicKit Searches back to my SwiftUI view. Normally I would use a @State variable for the decodable structure, but with MusicKit you dont need to decode anything and I can't figure out how to best get the data back to my view. I call the MusicKit function using .onAppear in my SwiftUI view func getAlbum() async throws -> MusicItemCollection<Album> {         var request = MusicCatalogResourceRequest<Album>(matching: \.id, equalTo: "1440881121")         let response = try await request.response()         print(response.debugDescription)         return response.items        printing debugDescription give these results: MusicCatalogResourceResponse<Album>(   items: [     Album(       id: "1440881121",       title: "Colors",       artistName: "Beck",       contentRating: "explicit",       copyright: Fonograf Records/Capitol Records; ℗ 2017 Fonograf Records, under exclusive license to UMG Recordings, Inc.,       genreNames: [         "Alternative",         "Music"       ],       isCompilation: false,       isComplete: true,       isDigitalMaster: true,       isSingle: false,       releaseDate: "2017-10-13",       trackCount: 11,       upc: "00602557176827" Hoe would you access all of the data in the debugDescription and use it in your SwiftUI view? I can only access the standard name and id. Is anyone using Codable to move the data through a data model? The documentation is not making sense to me even though I am usually ok using it. Also, should I be using `func getAlbum() async throws -> MusicCatalogResourceResponse {' instead of using MusicItemCollection? Thanks
Replies
8
Boosts
0
Views
2.7k
Activity
Jan ’22
is it possible to use gestures with SwiftUI Table?
I am using SwiftUI for Mac OS and so far I have not been able to implement tap gestures. I want to double click on a row of the Table and have that perform an action using the contents of that row. Does anyone know if it is even possible to use the .onTapGesture or anything similar to a SwiftUI Table? Any help is appreciated! Thanks!
Replies
2
Boosts
0
Views
2.5k
Activity
Jan ’22