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
1 Replies
125 Views
In SwiftUI there is a built-in component for displaying album artworks called Artwork but there is no equivalent for UIKit. My current approach is to use the .url() method to read image's URL and download the image or read it from the disk but the performance is much worse than it was previously with MPMediaItem's artworkImage method. let artworkQueue = DispatchQueue( label: "MusicKit-ArtworkQueue", qos: .default, attributes: .concurrent ) let artworkSemaphore = DispatchSemaphore(value: 5) extension Song { func artworkImage(for size: CGSize, completion: @escaping (UIImage?) -> Void) { artworkQueue.async { artworkSemaphore.wait() defer { artworkSemaphore.signal() } let imageURL = artwork?.url( width: Int(size.width), height: Int(size.height) ) // I hate doing this as it might very well break in the future guard let imageURL, imageURL.scheme == "musicKit" else { return completion(nil) } guard let imageData = try? Data(contentsOf: imageURL), let image = UIImage(data: imageData) else { return completion(nil) } completion(image) } } } I really dislike this approach because it feels hacky but somewhat works. You might ask what's the semaphore for? Well, without it I could notice that MusicKit was choking and after reading too many artworks at once. Can someone from Apple please provide us with an example on how to use MusicKit with UIKit properly? Ideally (IMO) we would have a method defined on Song and other MusicKit structures that returns the image for us, just like MPMediaItem had the .artwork() method. It would make our lives so much easier.
Posted
by wiencheck.
Last updated
.
Post not yet marked as solved
0 Replies
87 Views
Some users of our app get a black screen when playing mp4 files on their phones. The users are all running iOS 17.3.1 and cannot catch the error message when playing a black screen. The user can play the video normally after restarting the mobile phone. However, we want to solve this problem from the code. We use two Avplayers to complete the sequential playback of multiple videos. override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(videoPlayerA) layer.addSublayer(videoPlayerB) } lazy var layers = [videoPlayerA, videoPlayerB] lazy var videoPlayerA: AVPlayerLayer = { let avPlayerLayer = AVPlayerLayer(player: AVPlayer()) avPlayerLayer.contentsScale = UIScreen.main.scale avPlayerLayer.videoGravity = .resizeAspectFill return avPlayerLayer }() lazy var videoPlayerB: AVPlayerLayer = { let avPlayerLayer = AVPlayerLayer(player: AVPlayer()) avPlayerLayer.contentsScale = UIScreen.main.scale avPlayerLayer.videoGravity = .resizeAspectFill return avPlayerLayer }() func play() { if let path = paths[safe: currentIndex] { currentVideoPath = path currentPlayer = AVPlayer(playerItem: AVPlayerItem(url: URL(fileURLWithPath: path))) layers.first?.player?.pause() layer.insertSublayer(layers.first ?? AVPlayerLayer(), below: layers.last) layers.swapAt(0, 1) layers.first?.player = currentPlayer layers.first?.player?.play() SHPlayerGlobalStatus.sharedInstance.isLocalPlayerPlaying = true try? AVAudioSession.sharedInstance().setCategory(.playback) try? AVAudioSession.sharedInstance().setActive(true) }
Posted
by Grace1124.
Last updated
.
Post not yet marked as solved
1 Replies
865 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 breq.
Last updated
.
Post not yet marked as solved
0 Replies
106 Views
Hello, Can we use below mentioned keys in our code :- _MRMediaRemotePlayerPlaybackStateDidChangeNotification kMRMediaRemotePlaybackStateUserInfoKey Thanks
Posted Last updated
.
Post marked as solved
1 Replies
174 Views
I want to create a CPListImageRowItem/CPGridTemplate for the audio app which supports from iOS 13. for iOS14 and above I can able to do that with CPGridTemplate/ CPListImageRowItem but in iOS 13 how can we do? Because to support audio app from iOS13 I am using MPPlayableContentManager. So, are we able to achieve it iOS 13? Grid Should look like below image Please Suggest any way to achieve this kind of design? Thanks in advance.
Posted Last updated
.
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 AppWriter.
Last updated
.
Post not yet marked as solved
1 Replies
178 Views
I'm trying to accomplish creating a new playlist on device that appears in AppleMusic, and adding into the playlist a selection of MP3s within a small IOS app. Now the MP3's are either a stream of bytes, or a flat file already stored on the device (the app itself generates these - they aren't downloaded, they are created in app, and then stored on the local device) in it's local storage space. The idea is that created tracks can show up in a specific play list on the device. Now, there appears to be some conflict as to what framework I need to use. I've found MPMediaPlayer, which appears to allow me to create a playlist using the GetPlaylist call, although the documentation on this seems pretty sparse and there's not a lot of examples I can find on how to use this? It looks like a UUID is passed in, but there is no documentation on what this UUID is or where it comes from? If I want to create a new Playlist, I presume I need to generate a UUID, and then store that locally in order to be able to access that playlist again later, yes? There's an AddItem call which looks like it's how you add a track to a playlist, but there's no documentation on how you generate an entry. The documentation for this function talks about a Product ID, without describing what the product ID is, or where it needs to come from. Is this a GUID? Is it a name/description? Does it have to be unique? I'm assuming this Product ID refers to that which is being added to the playlist, but the documentation is sadly lacking in terms of explaining what the product ID refers to. Is it a media Item, or is that what is created when whatever entity the Product ID is referring to is added to the playlist? I'm assuming I can create a NSURL of the file that is stored that is actually the MP3 sample, but what I do with that in order to actually add it as a playlist entry is unknown. I'm sure there is a mechanism to do this, it's just not clear what that is. There's a lack of understanding or explanation of what the process is here, and some illumination would be helpful.
Posted Last updated
.
Post not yet marked as solved
0 Replies
208 Views
Hello everyone, my name is Joshua Osagie. For 2 months now, I have been trying to build my own music application, but unfortunately, I can’t because I was thinking I would get an API from maybe Apple Music or Spotify that will grant me access to over 100 million music. Even if the API is paid for, I have been doing my research, but then it's kind of impossible. So please, if anyone has an idea on what I can do to bring this application to life, I will really appreciate it. Or if anyone could share me an idea on how to get over millions of music on my app, I will be really grateful.
Posted Last updated
.
Post not yet marked as solved
1 Replies
367 Views
Hello everyone, I was playing a livestream when I received the error -16831/START-TIME is too close to live returned from the AVPlayerItemNewErrorLogEntry function. I don't know why the error is returned, please help me explain. Similarly, I am also getting error: -12888/Playlist File unchanged for longer than 1.5 * target duration , I also read error -12888 in the documentation page 170: https://docs.huihoo.com/apple/wwdc/ 2018/502_measuring_and_optimizing_hls_performance.pdf but still don't understand the reason. Hope you can help!
Posted Last updated
.
Post not yet marked as solved
0 Replies
221 Views
I play livestream thì bị lỗi : -12888 -"Playlist File unchanged for longer than 1.5 * target duration" , I also read error -12888 in the documentation page 170: https://docs.huihoo.com/apple/wwdc/ 2018/502_measuring_and_optimizing_hls_performance.pdf but still don't understand the reason. Please explain to me the reason for the error?
Posted Last updated
.
Post not yet marked as solved
0 Replies
205 Views
Hello everyone, I was playing a livestream when I received the error -16831/START-TIME is too close to live returned from the AVPlayerItemNewErrorLogEntry function. I don't know why the error is returned.Can you explain to me the reason for this error?
Posted Last updated
.
Post not yet marked as solved
0 Replies
225 Views
Hello, I don't run a podcast, therefore, I am not referring to the apple podcasts connect platform, and have been trying to get in contact with someone at Apple Podcasts. I would like to talk to developer support or someone who could consult on how to best approach something i'd like to build as an open source tool. I listen to a lot of podcasts and would like an analytics dashboard and toolset to take notes from the podcasts that I listen to on Apple Podcasts. Although, it would be just a good start to have analytics, accessing all of the info. I need to be able to plug into an API and pull all of that data from my account. Is there any way I can access this or talk to someone about this? I have a lot of historical data I assume from all of the shows i'm subscribed to and would like to visualize all of this. Is this possible? From my research, it seems that there is no way to access the information from the Podcasts app? Is there any infra for this?
Posted
by jozzy.
Last updated
.
Post not yet marked as solved
0 Replies
378 Views
Running in a Mac (Catalyst) target or Apple Silicon (designed for iPad). Just accessing the playbackStoreID from the MPMediaItem shows this error in the console: -[ITMediaItem valueForMPMediaEntityProperty:]: Unhandled MPMediaEntityProperty subscriptionStoreItemAdamID. The value returned is always “”. This works as expected on iOS and iPadOS, returning a valid playbackStoreID. import SwiftUI import MediaPlayer @main struct PSIDDemoApp: App { var body: some Scene { WindowGroup { Text("playbackStoreID demo") .task { let authResult = await MPMediaLibrary.requestAuthorization() if authResult == .authorized { if let item = MPMediaQuery.songs().items?.first { let persistentID = item.persistentID let playbackStoreID = item.playbackStoreID // <--- Here print("Item \(persistentID), \(playbackStoreID)") } } } } } } Xcode 15.1, also tested with Xcode 15.3 beta 2. MacOS Sonoma 14.3.1 FB13607631
Posted
by gbuela.
Last updated
.
Post not yet marked as solved
1 Replies
352 Views
Hey there, I'm trying to display all user's albums using the MediaPlayer library. I'm getting many albums returning nil, but I know artwork exists because they show up in the default Music app. There doesn't seem to be much rhyme or reason for what shows up and what doesn't. All downloaded albums display artwork, but some cloud album artwork displays as well. Here's the code I'm using to debug this. let query = MPMediaQuery.albums() if let albumCollections = query.collections { albums = albumCollections } for album in albums { let artwork = album.representativeItem?.artwork print(artwork, artwork?.image(at: CGSize(width: 100, height: 100))) } Any help would be greatly appreciated. Thanks!
Posted
by pjonori.
Last updated
.
Post not yet marked as solved
0 Replies
520 Views
According to docs the webkitEnterFullScreen() only works in IOS if the element is <video>, but own after i have updated to IOS 17.1.2 it's not working, i have tested it in chrome and safari both. Even the test code W3School for Fullscreen does not work in IOS 17.1.2 Test Done Model: 1Phone 15 pro max IOS Version: 17.0.2 Browser: Chrome Test URL https://www.w3schools.com/howto/howto_js_fullscreen.asp
Posted Last updated
.
Post not yet marked as solved
0 Replies
327 Views
Hello Dev, Recently my client reported freezing the app screen when trying to dismiss it. Our application is related to music. When I checked the flow on the Simulator, I got the same case on the iPhone 15 series. I debugged the code and what I saw was CPU usage got 100% when I tried to pull down the model presented popover controller. I have checked the same flow multiple times and it worked 3-4 times and Additionally, it worked on some real devices and simulators too. So I can't understand what causing this issue. Can you please help me on this? I'm looking forward to hearing from you. Thank you in advance!
Posted
by UM5468.
Last updated
.
Post not yet marked as solved
0 Replies
352 Views
Hi, In iOS 17.0 Apple introduced a favorite button for the music app. This favorite button is available everywhere including Control Center and CarPlay. My question is if there is a way to show/use this favorite button in my own app. Couldn't find it in the documentation. Thank you..!
Posted
by wotson.
Last updated
.