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

85 Posts
Sort by:
Post not yet marked as solved
6 Replies
3.9k 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.6k 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.8k 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 not yet marked as solved
24 Replies
7.2k Views
Just wondering if anyone else is having issues with currentPlaybackRate in release version of iOS 15.4? In my particular case this is using MPMusicPlayerController.applicationQueuePlayer. I've always had issues controlling this property reliably but from what I can see it is now completely non-operational in 15.4. I've isolated this behavior in a trivial project, and will file a radar, but hoping others may have some insight first. FWIW- This is my trivial test case: class ViewController: UIViewController {     lazy var player: MPMusicPlayerApplicationController = {         let player = MPMusicPlayerController.applicationQueuePlayer         player.repeatMode = .none         player.shuffleMode = .off         player.beginGeneratingPlaybackNotifications()         return player     }()     override func viewDidLoad() {         super.viewDidLoad()         NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: nil, queue: .main) { [weak self] notification in             guard let notificationPlayer = notification.object as? MPMusicPlayerApplicationController,                   notificationPlayer === self?.player else {                 return             }                          debugPrint("Player state now: \(notificationPlayer.playbackState)")         }     }     @IBAction func goAction(_ sender: Any) {         guard let item = MPMediaQuery.songs().items?.randomElement() else {             debugPrint("Unable to access media items")             return         }         debugPrint("Now playing item: \(item.title ?? "")")         player.setQueue(with: [item.playbackStoreID])         player.prepareToPlay() { error in             guard error == nil else {                 debugPrint("Player error: \(error!.localizedDescription)")                 return             }             DispatchQueue.main.async { [weak self] in                 self?.player.play()             }         }     } @IBAction func slowAction(_ sender: Any) {         debugPrint("Setting currentPlaybackRate to 0.5")         player.currentPlaybackRate = 0.5         checkPlaybackRate()     } @IBAction func fastAction(_ sender: Any) {         debugPrint("Setting currentPlaybackRate to 1.5")         player.currentPlaybackRate = 1.5         checkPlaybackRate()     } func checkPlaybackRate(afterSeconds delay: TimeInterval = 1.0) {         DispatchQueue.main.asyncAfter(deadline: .now() + delay) {             debugPrint("After \(delay) seconds currentPlaybackRate now: \(self.player.currentPlaybackRate)")         }     } } Typical console output: "Now playing item: I Know You Know" "Player state now: MPMusicPlaybackState(rawValue: 2)" "Player state now: MPMusicPlaybackState(rawValue: 1)" "Setting currentPlaybackRate to 1.5" "After 1.0 seconds currentPlaybackRate now: 1.0" "Setting currentPlaybackRate to 0.5" "After 1.0 seconds currentPlaybackRate now: 1.0"
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
1.9k 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.8k 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
2k 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
669 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
3 Replies
1.4k 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
1 Replies
703 Views
Using quicktime play mp4 file, an error occurred and the document "XX. mp4" could not be opened. An unknown error occurred (-12842), and with Safari browser, only the first keyframe can be played and the video will become stuck. Both Chrome and Firefox can play [normally]
Posted
by
Post not yet marked as solved
0 Replies
446 Views
I have a song playlist whose element is MPMediaItem, and I want to share this song playlist, so my original plan was to use persistentID as the identification of the song, but I found that persistentID does not seem to be able to cross devices, use MPMediaQuery persistentID to query the result is empty. So my question is? In this case, what should I do to share this playlist, so that other users can find the corresponding song to play after getting the playlist.
Posted
by
Post not yet marked as solved
0 Replies
462 Views
I'm trying to configure the "Now Playing" information for my app on iOS. Using MPNowPlayingInfoCenter/MPRemoteCommandCenter is pretty straightforward for this. The issue I'm having is that the audio I'm playing is generated "on the fly" and I do not know the exact duration in seconds. I am able to synthesize an NSProgress to display the progress of the playback but the units are not in seconds. So if I use the NSProgress units with MPNowPlayingInfoCenter the "Now Playing" shows the units in seconds but it appears to be jumpy (because again my progress units are not in seconds but an approximation of the percent completed). [playInfo setObject:@(self.progress.totalUnitCount) forKey:MPMediaItemPropertyPlaybackDuration]; [playInfo setObject:@(self.progress.completedUnitCount) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; I see there is a MPNowPlayingInfoPropertyPlaybackProgress which looks like it would be perfect. I tried setting that instead of MPMediaItemPropertyPlaybackDuration/MPNowPlayingInfoPropertyElapsedPlaybackTime but it appears to have no effect in the "Now Playing" UI. I also tried setting MPNowPlayingInfoPropertyIsLiveStream to YES but that just makes the "Now Playing" UI display "Live" instead of the progress value. Is there a way I can show a progress bar without the units being displayed in seconds? Thanks in advance.
Post not yet marked as solved
0 Replies
637 Views
I have an idea for an iOS App that involves creating alarms and "undismissable" notifications. Currently, iOS has multiple system features like silent/ring mode, focus mode, security protections, and other system features that would limit the functionality of an app with this purpose. Basically, think of a system Amber Alert or how the iOS Alarm app works. Regardless of these system settings, the user will be notified of the importance of the alarm immediately. What I'm trying to develop are really two separate things. First an alarm app without a snooze (or a set snooze limit) where you must prove that you're awake. Second, integrate a web API service for volunteer first responders that notify them to respond to an emergency via an iOS app. These are not features that would limit a user's privacy, their experience using iOS, and, quite frankly, be something that is so difficult to implement. If anyone can direct me to any system APIs that would be available to use for the start of this app or make me aware of any "blockers" that would absolutely prevent me from developing this in iOS, I would really appreciate it. My research has not been very in depth and there are differences in opinions on approaches and possibilities. If you are an engineer at Apple and this turns out to be impossible or impractical with current versions of iOS, it would be great to have the ability to be able to do something of this nature in the future.
Posted
by
Post not yet marked as solved
0 Replies
508 Views
private func updateNowPlayingInfo() { var nowPlayingInfo = [String: Any]() nowPlayingInfo[MPMediaItemPropertyTitle] = songLabel.text nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = Int(Double(audioLengthSamples) / audioSampleRate) nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = Int(Double(currentPosition) / audioSampleRate) print(isPlaying) print("updateNow") let playbackRate = isPlaying ? self.timeEffect.rate : 0.0 print(playbackRate) nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = playbackRate MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } Whenever I press my play/pause button in the app, I expect control center and the lock screen to reflect this. However, control center symbols stays as pause regardless of what I do in the app. Am I missing anything? Running on device with iOS 16.4.1. private func configureRemoteCommandCenter() { let commandCenter = MPRemoteCommandCenter.shared() // Play command commandCenter.playCommand.isEnabled = true commandCenter.playCommand.addTarget { [weak self] event in // Handle the play command self?.playOrPauseFunction() return .success } // Pause command commandCenter.pauseCommand.isEnabled = true commandCenter.pauseCommand.addTarget { [weak self] event in // Handle the pause command self?.playOrPauseFunction() return .success } commandCenter.togglePlayPauseCommand.isEnabled = true commandCenter.togglePlayPauseCommand.addTarget { [weak self] event in self?.playOrPauseFunction() return .success } commandCenter.changePlaybackRateCommand.isEnabled = true commandCenter.changePlaybackPositionCommand.isEnabled = true commandCenter.changePlaybackPositionCommand.addTarget { [unowned self] event in guard let event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed } currentPosition = AVAudioFramePosition(event.positionTime * audioSampleRate) scrubSeek(to: Double(currentPosition)) updateNowPlayingInfo() return .success } // Add handlers for other remote control events here... }
Posted
by