我正在我的 swiftui 应用程序中设置一个非常简单的媒体播放器。
代码如下:
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()
}
}
很有学术性。
该代码在视图上调用时有效。它也会显示在锁屏/动态岛中(在后台时),但问题在于:
许多音频应用程序运行良好,所以我的代码是否缺少一些东西。但我不知道为什么。 缺少什么?
好吧,最终问题仅限于模拟器上。在真实设备上工作没有任何问题