-2

我似乎找不到解决此问题的方法。我正在使用 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)
    }
}
4

1 回答 1

0

您不会创建自己的实例。使用任一:

var mediaPlayer = MPMusicPlayerController.applicationMusicPlayer

或者:

var mediaPlayer = MPMusicPlayerController.applicationQueuePlayer

或者:

var mediaPlayer = MPMusicPlayerController.systemMusicPlayer

取决于你的需要。MPMusicPlayerController有关详细信息,请参阅参考文档。

于 2019-02-20T21:05:44.267 回答