Media Player

RSS for tag

Find and play songs, audio podcasts, audio books, and more from within your app using Media Player.

Media Player Documentation

Posts under Media Player tag

84 Posts
Sort by:
Post not yet marked as solved
6 Replies
4k Views
I'm getting a variety of errors when I call prepareToPlay on the MPMusicPlayerController. Sometimes they happen, sometimes they don't. I'm trying to play songs from the Apple Music service. When I don't get the errors, it plays just fine. I have iOS v13.5.1 on my iPhone Xs and I'm using Xcode 11.5. This is my code: let applicationMusicPlayer = MPMusicPlayerController.applicationMusicPlayer applicationMusicPlayer.setQueue(with: [trackID]) applicationMusicPlayer.prepareToPlay(completionHandler:{ error in if let error = error { print(error.localizedDescription) return } DispatchQueue.main.async{ applicationMusicPlayer.play() } } These are the various errors I'm getting: [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=2 "Queue was interrupted by another queue" UserInfo={NSDebugDescription=Queue was interrupted by another queue} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=9 "Preparing queue timed out" UserInfo={NSDebugDescription=Preparing queue timed out} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong]
Posted
by
Post marked as solved
11 Replies
3.7k Views
I'm playing library items (MPMediaItem) and apple music tracks (Track) in MPMusicPlayerApplicationController.applicationQueuePlayer, but I can't use the actual Queue functionality because I can't figure out how to get both media types into the same queue. If there's a way to get both types in a single queue, that would solve my problem, but I've given up on that one. Because I can't use a queue, I have to be able to detect when a song ends so that I can put the next song in the queue and play it. The only way I can figure out to detect when a song ends is by watching the playBackState, and I've actually got that pretty much working, but it's really ugly, because you get playBackState of paused when a song ends, and when a bluetooth speaker disconnects, etc. The only answer I've been able to find on the internet is to watch the MPMusicPlayerControllerNowPlayingItemDidChange, and when that fires, and the nowPlayingItem is NIL, a song ends.. but that's not the case. When a song ends, the nowPlayingItem remains the same. There's got to be an answer to this problem, right?
Posted
by
Post not yet marked as solved
2 Replies
1.9k Views
Hello, I'm using systemMusicPlayer to play Apple Music Live Radio Station got from Apple Music API. But it doesn't work. How can I do that? Error: Test[46751:13235249] [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} My implementation:    let musicPlayerController = MPMusicPlayerController.systemMusicPlayer musicPlayerController.beginGeneratingPlaybackNotifications()      musicPlayerController.setQueue(with: "ra.978194965")     musicPlayerController.play() API response: { “id”: “ra.978194965”, “type”: “stations”, “href”: “/v1/catalog/us/stations/ra.978194965”, “attributes”: { “artwork”: { “width”: 4320, “url”: “https://is2-ssl.mzstatic.com/image/thumb/Features114/v4/e5/10/76/e5107683-9e51-ebc5-3901-d8fbd65f2c2a/source/{w}x{h}sr.jpeg”, “height”: 1080, “textColor3”: “332628”, “textColor2”: “120509”, “textColor4”: “33272a”, “textColor1”: “000000”, “bgColor”: “f4f4f4”, “hasP3”: false }, “url”: “https://music.apple.com/us/station/apple-music-1/ra.978194965”, “mediaKind”: “audio”, “supportedDrms”: [ “fairplay”, “playready”, “widevine” ], “requiresSubscription”: false, “name”: “Apple Music 1”, “kind”: “streaming”, “radioUrl”: “itsradio://music.apple.com/us/station/ra.978194965”, “playParams”: { “id”: “ra.978194965”, “kind”: “radioStation”, “format”: “stream”, “stationHash”: “CgkIBRoFlaS40gMQBA”, “mediaType”: 0 }, “editorialNotes”: { “name”: “Apple Music 1”, “short”: “The new music that matters.”, “tagline”: “The new music that matters.” }, “isLive”: true } },``` Thank you! Best regards, MichaelNg
Posted
by
Post marked as solved
2 Replies
1.6k Views
Hey there Apple Music team! I'm excited to dig into the sessions coming up this week, and what I've seen so far from the developer documentation diffs looks great: audio quality, artist images, and a way to interface with a user's music library in MusicKit. Love it! The thing at the very top of my WWDC wishlist this year was macOS/Mac Catalyst support for the ApplicationMusicPlayer class. I just got finished installing Ventura and Xcode 14, and sadly it looks like the support story is the same as on Big Sur. No API availability on macOS, and an available Mac Catalyst API that ultimately results in the same error from a feedback I submitted on Big Sur: FB9851840 The connection to service named com.apple.Music.MPMusicPlayerApplicationControllerInternal was invalidated: failed at lookup with error 3 - No such process. Is that the end of the story on Ventura, or is there a chance support might be added in a later beta? Is there any additional detail at all that can be shared? I field several requests a week asking if/when my app is coming to the Mac, and I would really love to be able to make that happen. If there is anything at all I can do to test and help overcome the engineering challenges alluded to in the past, I am ready, willing, and able! In any case, thanks for the great work, and I'm looking forward to spending time with the new stuff this summer.
Posted
by
Post not yet marked as solved
4 Replies
2.0k Views
Hey there, we're using a CDN with HTTP referer checks in place for streaming media. When streaming with Airplay, what is the referer set on the HTTP header? For instance, for Google Chromecast, it's: https://www.gstatic.com/
Posted
by
Post not yet marked as solved
2 Replies
1.2k Views
We noticed iOS 16 doesn't seem to support these commands anymore: MPRemoteCommandCenter.shared().likeCommand MPRemoteCommandCenter.shared().dislikeCommand MPRemoteCommandCenter.shared().bookmarkCommand Or is there another way to show a menu in lieu of the previous button on the lock screen?
Posted
by
Post not yet marked as solved
4 Replies
1.9k Views
Hi I have this piece of code in my app that is supposed to open up a file from Music(old iTunes) app and play. But I get 'Attempted to register account monitor for types client is not authorized to access "com.apple.account.iTunesStore". Any suggests how to fix this. What entitlements do I need to set? Code and error logs are below code-block ``` func showiPOD() {           let mediaPicker: MPMediaPickerController = MPMediaPickerController.self(mediaTypes:MPMediaType.anyAudio)     mediaPicker.delegate = self as MPMediaPickerControllerDelegate     mediaPicker.allowsPickingMultipleItems = false     mediaPicker.showsCloudItems = true //show from iCloud as well.. needs to be tested     self.present(mediaPicker, animated: true, completion: nil)   } 2023-01-24 09:31:22.018992-0800 Smart Practice[526:16253] [Entitlements] MSVEntitlementUtilities - Process Smart Practice PID[526] - Group: (null) - Entitlement: com.apple.accounts.appleaccount.fullaccess - Entitled: NO - Error: (null) 2023-01-24 09:31:22.022520-0800 Smart Practice[526:16253] [core] Attempted to register account monitor for types client is not authorized to access: {(   "com.apple.account.iTunesStore" )} ```language code-block
Posted
by
Post not yet marked as solved
2 Replies
2.1k Views
I'm developing a media player for Mac (AppKit, not Catalyst) that plays local and remote content. I have AirPlay working with AVPlayer (with an AVRoutePickerView assigning the route), but while I get the metadata that I've set for the MPNowPlayingInfoCenter on the AirPlay device (a TV in this case), I don't get any album art (but I do in the macOS now playing menu bar/control centre applet). It looks like this: (imgur link because I can't get it to upload in the forum): https://i.imgur.com/2JBIYCw.jpg My code for setting the metadata:         NSImage *artwork = [currentTrack coverImage];         CGSize artworkSize = [artwork size];         MPMediaItemArtwork *mpArtwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:artworkSize requestHandler:^NSImage * _Nonnull(CGSize size) {             return artwork;         }];         [songInfo setObject: mpArtwork forKey:MPMediaItemPropertyArtwork]; I noticed that it doesn't resize, but it seems at least macOS doesn't care. I tried modifying the code to resize the artwork in the callback, but that also doesn't change anything. I noticed in the logs that I get a message about a missing entitlement: 2023-01-29 14:00:37.889346-0400 Submariner[42682:9794531] [Entitlements] MSVEntitlementUtilities - Process Submariner PID[42682] - Group: (null) - Entitlement: com.apple.mediaremote.external-artwork-validation - Entitled: NO - Error: (null) ...however, this seems to be a private entitlement and the only reference I can find to it is WebKit. Using it makes LaunchServices very angry at me, and I presume it's a red herring.
Posted
by
Post not yet marked as solved
1 Replies
709 Views
Hi, I’m looking at using MusicKit in my watchOS app however I don’t seem to have any method of being able to play the audio though the recommended use of MPMusicPlayerController since it isn’t available on watchOS. This method works fine for iOS and iPadOS but not watchOS which seems bizarre considering we have full access to MusicKit but no way to actually play any audio. I’m trying to build an app that includes Apple Music through MusicKit but don’t have any way to actually play the audio. Is there a technical reason for this and if so is there any other way to play audio from MusicKit on watchOS. The docs for MPMusicPlayerController can be found here: https://developer.apple.com/documentation/mediaplayer/mpmusicplayercontroller
Posted
by
Post not yet marked as solved
4 Replies
1.5k Views
I'm using applicationQueuePlayer in my application. I set Queue for it and it plays music. It was working fine in the app installed on my phone, but after phone was updated to iOS 16.4 it stopped working (see errors below). When I remove app from phone and recompiled and re-installed it to that phone, player started working normally. But when I replaced container via Xcodes Device and Simulators to previously saved - it stopped working again. Re-installing it on top of existing didn't fix it. It was only working if removed from phone completely and then installed from Xcode "from scratched". This started happening after phone update to 16.4. When I installed app "from scratch" - it was working fine, but when 16.4.1 was release couple of days ago and I installed it on a phone, it again broke the applicationQueuePlayer in my app. Same thing - removing app from phone and installing from scratch from Xcode makes it work, but restoring old container via Devices and Simulators breaks it again. I presume it has something to do with entitlements, but can't find any notes or info. Please help! Errors in log after attempting to start playing a title: 2023-04-12 14:56:19.400111-0400 MicyclePro[26736:2608042] [core] Attempted to register account monitor for types client is not authorized to access: {( "com.apple.account.iTunesStore" )} 2023-04-12 14:56:19.400284-0400 MicyclePro[26736:2608042] [Default] <ICMonitoredAccountStore: 0x2834ef390> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)" 2023-04-12 14:56:20.407123-0400 MicyclePro[26736:2608714] [SDKPlayback] SYNC-WATCHDOG-1: Attempting to wake up the remote process 2023-04-12 14:56:20.619230-0400 MicyclePro[26736:2608439] [SDKPlayback] applicationController: xpc service connection interrupted 2023-04-12 14:56:20.619376-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service with pid 26768 created from an endpoint" UserInfo={NSDebugDescription=connection to service with pid 26768 created from an endpoint} 2023-04-12 14:56:20.619816-0400 MicyclePro[26736:2608512] [SDKPlayback] applicationMusicPlayer: connection invalidated 2023-04-12 14:56:20.620993-0400 MicyclePro[26736:2608042] [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong] 2023-04-12 14:56:20.621094-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003." UserInfo={NSDebugDescription=The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003.} 2023-04-12 14:56:20.621376-0400 MicyclePro[26736:2608042] [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong] 2023-04-12 14:56:20.621411-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003." UserInfo={NSDebugDescription=The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003.} 2023-04-12 14:56:20.628535-0400 MicyclePro[26736:2608042] [SystemGestureGate] <0x10761aa20> Gesture: System gesture gate timed out.
Posted
by
Post not yet marked as solved
0 Replies
608 Views
Hello, Here is an issue I encountered recently. Does anybody have feedback on this? Issue encountered AVAudioFile throws when opening WAV files and MPEG-DASH files with .mp3 extension, works fine with many other tested combinations of formats and extension (for example, an AIFF file with .mp3 extension is read by AVAudioFile without error). The Music app, AVAudioFile and ExtAudioFile all fail on the same files. However, previewing an audio file in Finder (select the file and hit the space bar) works regardless of the file extension. Why do I consider this an issue? AVAudioFile seems to rely on extension sometimes but not always to guess the audio format of the file, which leads to unexpected errors. I would expect AVAudioFile to deal properly with wrong extensions for all supported audio formats. ⚠️ This behaviour can cause real trouble in iOS and macOS applications using audio files coming from the user, which often have unreliable extensions. I published some code to easily reproduce the issue: https://github.com/ThomasHezard/AVAudioFileFormatIssue Thank you everybody, have a great day 😎
Posted
by
Post not yet marked as solved
0 Replies
544 Views
I am simply trying to visualize m3u8 files from my Amazon S3 server while they are playing on my AVPlayer. The basic context of my AVPlayer is that I first create AVURLAsset and attach the cookies required to access it and then subsequently create the AVPlayerItem. I then setup the AVPlayer, play it, and then setup an observer so that I can handle some logic when the audio file is done playing. I just want to be able to get the power data of the streamed file in real time or close to real time. I looked into audioTapProcessor but it does not appear to work with streamed files. I then looked into AVAudioEngine but that also does not work well with streams. Is there any solution to this?
Posted
by
Post not yet marked as solved
1 Replies
974 Views
I am learning SwiftUI, I want to observe an AVPlayer status so I know when the videos is paused or not. My current approach is more less like this: I have VideosView that holds a list of a videos (in ZStack cards). VideoViews has a VideosViewModel. in VideosView i am calling in onAppear VideosViewModel.getItems... struct ItemModel: Identifiable, Codable, Hashable, Equatable { var id: String var author: String // video owner var url: URL? // url to the video var player: AVPlayer? // AVPlayer created based on self.url... mutating func setPlayer(_ avPlayer: AVPlayer) { self.player = avPlayer } } // vm class FeedViewModel: ObservableObject { @Published private(set) var items: [ItemModel] = [] func getItems() async { do { // fetch data from the API let data = try await dataService.fetchFeeds() // download and attach videos downloadFeedVideos(data) } catch { // .... } } private func downloadFeedVideos(_ feeds: [ItemModel]) { for index in feeds.indices { var item = feeds[index] if let videoURL = item.url { self.downloadQueue.queueDownloadIfFileNotExists( videoURL, DownloadOperation( session: URLSession.shared, downloadTaskURL: videoURL, completionHandler: { [weak self] (localURL, response, error) in guard let tempUrl = localURL else { return } let saveResult = self?.fileManagerService.saveInTemp(tempUrl, fileName: videoURL.lastPathComponent) switch saveResult { case .success(let savedURL): DispatchQueue.main.async { // maybe this is a wrong place to have it? item.setPlayer(AVPlayer(url: savedURL)) self?.items.append(item) if self?.items.count ?? 0 > 1 { // once first video is downloaded, use all device cores to fetch next videos // all newest iOS devices has 6 cores self?.downloadQueue.setMaxConcurrentOperationCount(.max) } } case .none: break case .failure(_): EventTracking().track("Video download fail", [ "id": item.id, "ulr": videoURL.absoluteString.decodeURL() ]) } }), { fileCacheURL in // file already downloaded DispatchQueue.main.async { item.setPlayer(AVPlayer(url: fileCacheURL)) self.items.append(item) } }) } } } } I found this article with some pseudo-code of how to track video playback state but I'm not sure how to implement it in my code.... https://developer.apple.com/documentation/avfoundation/media_playback/observing_playback_state
Posted
by
Post not yet marked as solved
0 Replies
712 Views
I want to use AVPlayerViewController to display the video but it should be in auto-play mode. Previously I was using AVPlayer for that and listening to the .AVPlayerItemDidPlayToEndTime notification but I wonder if there is a better way? eg. using AVPlayerLooper for instance so I don't have to use that .AVPlayerItemDidPlayToEndTime anymore I wrote something like this but it is not working - I have a black screen with video controls - probably because AVPlayerViewController does not have any playable content... struct VideoPlayerQueuedView: UIViewControllerRepresentable { let videoUrl: URL func makeUIViewController(context: Context) -> AVPlayerViewController { let queuePlayer = AVQueuePlayer() let playerViewController = AVPlayerViewController() // Create an AVPlayerItem from the videoUrl let playerItem = AVPlayerItem(url: videoUrl) // Create an AVPlayerLooper with the queuePlayer and the playerItem as the template item let playerLooper = AVPlayerLooper(player: queuePlayer, templateItem: playerItem) // Set the player property of AVPlayerViewController playerViewController.player = queuePlayer return playerViewController } func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) { // Update the video player if needed } }
Posted
by
Post not yet marked as solved
1 Replies
1.4k Views
I'm getting the following error in Xcode and I can't figure out how to fix it. Cannot load underlying module for 'MediaPlayer' I've searched Google and have come across lots of other people with similar issues whereby they're importing something and it's producing this error alongside it. https://stackoverflow.com/questions/76256875/cannot-load-underlying-module-for-scenekit https://developer.apple.com/forums/thread/115059 https://stackoverflow.com/questions/32673866/cocoapods-cannot-load-underlying-module-for-x The error is being shown inline with this bit of code: import SwiftUI import MusicKit import MediaPlayer <-- this line here I can build and run the project without issue and it disappears. But will quickly reappear again a short while later and it's very annoying. How can I resolve this please?
Posted
by
Post not yet marked as solved
3 Replies
1.3k Views
Hello, We are using HLS for our streaming iOS and tvOS applications. We have DRM protection on our applications but we want add another secure layer which is CDN token. We want to add that CDN token data on header or query parameters. Any of two are applicable at our CDN side. There is a problem at client side. We want to send that token knowledge and refresh at given a time. We add token data using at initial state let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": headers]) and add interceptor with asset.resourceLoader.setDelegate. It works seamlessly. We use AVAssetResourceLoaderDelegate and we can intercept just master playlist and playlists via func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool and we can refresh CDN token data at only playlists. That token data can be at query params or header. It does not matter. For example, #EXTM3U #EXT-X-VERSION:3 #EXTINF:10.0 https://chunk1?cdntoken=A.ts #EXTINF:10.0 https://chunk2?cdntoken=A.ts #EXTINF:10.0 https://chunk3?cdntoken=A.ts #EXTINF:10.0 assume that it is our .m3u8 file for given live video playlist. It has three chunks with cdn token data in query params. If we give that chunks to AVPlayer. It is going to play chunks in order. When we change new cdn token at query params, it effects our chunk Urls and our player stalls. It is because our cdn adds new cdn token knowledge to chunk's Url. It means that our new .m3u8 is going to be like that for next playlist; #EXT-X-VERSION:3 #EXTINF:10.0 https://chunk4?cdntoken=B.ts #EXTINF:10.0 https://chunk5?cdntoken=B.ts #EXTINF:10.0 https://chunk6?cdntoken=B.ts #EXTINF:10.0 Cdn token data is converted to B from A at cdn side and it sends new playlist like that. That's why, our player is going to stall. Is there any way not to player stall with edited chunk url? When we change new cdn token at header. It does not change chunks url like at the first question but AVPlayer does not allow to intercept chunk Urls which means that before callin https://chunk1?cdntoken=A.ts url, i want to intercept and add new cdn token data to header. Is there any way to intercept chunk Urls like intercepting playlist? Thanks for answers in advance
Posted
by
Post not yet marked as solved
6 Replies
2k Views
Turn on address sanitizer on Xcode and use a real device and put a Test.mp3 file in the Xcode project. Then it will crash when you initialise a AVAudioPlayer with a mp3 file (with a wav file it works fine). I have made an entry in feedback assistent -> FB12425453. var player : AVAudioPlayer? func playSound() { if let url = Bundle.main.url(forResource: "Test", withExtension: "mp3") { self.player = try? AVAudioPlayer(contentsOf: url) // --> deallocation of non allocated memory problem --> with a "wav" file it works .... } }
Posted
by