我似乎找不到解决此问题的方法。我正在使用MusicKit,因此您可以通过我的应用播放音乐,但是我一直遇到错误。
import UIKit
import MediaPlayer
class ViewController: UIViewController, MPMediaPickerControllerDelegate {
@IBOutlet weak var playPause: UIButton!
@IBOutlet weak var artImg: UIImageView!
@IBOutlet weak var songLabel: UILabel!
// ERROR HERE
var mediaPlayer = MPMusicPlayerController()
@IBAction func chooseBtn(_ sender: Any) {
let mediaPickerVC = MPMediaPickerController(mediaTypes: .music)
mediaPickerVC.allowsPickingMultipleItems = false
mediaPickerVC.popoverPresentationController?.sourceView = view
mediaPickerVC.delegate = self
present(mediaPickerVC, animated: true, completion: nil)
}
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
for item in mediaItemCollection.items {
if let albumImage = item.artwork?.image(at: CGSize(width: 500, height: 500)) {
artImg.image = albumImage
if let title = item.title {
songLabel.text = title
}
}
}
mediaPicker.dismiss(animated: true, completion: nil)
mediaPlayer.setQueue(with: mediaItemCollection)
mediaPlayer.play()
}
func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) {
mediaPicker.dismiss(animated: true, completion: nil)
}
}
答案 0 :(得分:0)
您不创建自己的实例。使用以下任一方法:
var mediaPlayer = MPMusicPlayerController.applicationMusicPlayer
或:
var mediaPlayer = MPMusicPlayerController.applicationQueuePlayer
或:
var mediaPlayer = MPMusicPlayerController.systemMusicPlayer
取决于您的需求。有关更多详细信息,请参见MPMusicPlayerController
的参考文档。