这个问题已经问了很多,但是我一直遵循着每个步骤来创建Spotify控制中心。但是我的应用程序甚至没有显示标题和插图。
我播放音频的代码:
@IBAction func play(_ sender: Any) {
let videoURL = URL(string: "song url")
player = AVPlayer(url: videoURL!)
playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
self.playerViewController.updatesNowPlayingInfoCenter = true
self.playerViewController.player!.play()
}
}
背景播放代码:
//App enter in forground.
@objc func applicationWillEnterForeground(_ notification: Notification) {
// If presenting video with AVPlayerViewController
playerViewController.player = player
}
//App enter in forground.
@objc func applicationDidEnterBackground(_ notification: Notification) {
// If presenting video with AVPlayerViewController
playerViewController.player = nil
}
我的viewDidLoad()
:
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
addPlayerNotifications()
UIApplication.shared.beginReceivingRemoteControlEvents()
self.setupNowPlaying()
self.setupRemoteTransportControls()
}
在viewDidLoad()内部调用的函数:
func addPlayerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
func setupRemoteTransportControls() {
// Get the shared MPRemoteCommandCenter
let commandCenter = MPRemoteCommandCenter.shared()
// Add handler for Play Command
commandCenter.playCommand.addTarget { [unowned self] event in
if self.player.rate == 0.0 {
self.player.play()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { [unowned self] event in
if self.player.rate == 1.0 {
self.player.pause()
return .success
}
return .commandFailed
}
}
func setupNowPlaying() {
// Define Now Playing Info
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "YouTube Videos"
if let image = UIImage(named: "lockscreen") {
nowPlayingInfo[MPMediaItemPropertyArtwork] =
MPMediaItemArtwork(boundsSize: image.size) { size in
return image
}
}
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = player.currentItem?.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
// Set the metadata
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
框架和功能:
仍然。它没有显示我的图稿,并且控件不起作用:(