I'm setting up a really simple media player in my swiftui app.
the code is the following:
import AVFoundation
import MediaPlayer
class AudioPlayerProvider {
private var player: AVPlayer
init() {
self.player = AVPlayer()
self.player.automaticallyWaitsToMinimizeStalling = false
self.setupAudioSession()
self.setupRemoteCommandCenter()
}
private func setupAudioSession() {
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Failed to set up audio session: \(error.localizedDescription)")
}
}
private func setupRemoteCommandCenter() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget { [weak self] _ in
guard let self = self else { return .commandFailed }
self.play()
return .success
}
commandCenter.pauseCommand.addTarget { [weak self] _ in
guard let self = self else { return .commandFailed }
self.pause()
return .success
}
}
func loadAudio(from urlString: String) {
guard let url = URL(string: urlString) else { return }
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
self.player.pause()
self.player.replaceCurrentItem(with: playerItem)
NotificationCenter.default.addObserver(self, selector: #selector(self.streamFinished), name: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem)
}
func setMetadata(title: String, artist: String, duration: Double) {
var nowPlayingInfo = [
MPMediaItemPropertyTitle: title,
MPMediaItemPropertyArtist: artist,
MPMediaItemPropertyPlaybackDuration: duration,
MPNowPlayingInfoPropertyPlaybackRate: 1.0,
] as [String: Any]
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
@objc
private func streamFinished() {
self.player.seek(to: .zero)
try? AVAudioSession.sharedInstance().setActive(false)
MPNowPlayingInfoCenter.default().playbackState = .stopped
}
func play() {
MPNowPlayingInfoCenter.default().playbackState = .playing
self.player.play()
}
func pause() {
MPNowPlayingInfoCenter.default().playbackState = .paused
self.player.pause()
}
}
pretty scholastic.
The code works when called on views. It also shows up within the lock screen / dynamic island (when in background), but here lies the problems:
Many audio apps are working just fine so is my code lacking something. But I don't know why. What is missing?
Well, in the end the problem is limited on the simulator. Working on a real device shows no issue