UIImageView图像会随着不同的歌曲而变化

时间:2018-09-10 22:47:36

标签: ios swift media-player

我有一个简单的媒体播放器,我正在尝试使其随着歌曲的更改而更改图稿图像。使用现在的代码,当您点击播放时它将显示艺术品,但是当我按下下一个按钮以跳到下一个项目时,除非您按下另一个按钮,否则它将保持不变。

当歌曲媒体项目更改时,如何使UIImageView图像更改?

import UIKit
import MediaPlayer

class ViewController: UIViewController {
    @IBOutlet weak var coverImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createQueue()
    }

    func showArt(){
    coverImageView.image = 
    myMediaPlayer.nowPlayingItem?.artwork!.image(at: CGSize.init(width: 500, height: 500))
    coverImageView.isUserInteractionEnabled = true
    }

    @IBAction func playButton(_ sender: UIButton) {
    togglePlay(on: sender)
    showArt()
    }

    @IBAction func backButton(_ sender: UIButton) {
    back()
    }

    @IBAction func nextButton(_ sender: UIButton) {
    skip()
    }

}

我的其他功能如下:

import MediaPlayer

let myMediaPlayer = MPMusicPlayerApplicationController.systemMusicPlayer

let playDrake = MPMediaPropertyPredicate(value: "Drake", forProperty: MPMediaItemPropertyArtist, comparisonType: MPMediaPredicateComparison.equalTo)

let myFilterSet: Set<MPMediaPropertyPredicate> = [playDrake]

func createQueue() {
        let drakeQuery = MPMediaQuery(filterPredicates: myFilterSet)
        myMediaPlayer.setQueue(with: drakeQuery)
}

func skip() {
        myMediaPlayer.skipToNextItem()
}

func back() {
        if myMediaPlayer.currentPlaybackTime > 0.05 {
            myMediaPlayer.skipToPreviousItem()
        } else if myMediaPlayer.currentPlaybackTime < 0.05 {
            myMediaPlayer.skipToBeginning()
        } else {
            //do nothing
        }
    }


func togglePlay(on: UIButton) {
        if myMediaPlayer.playbackState.rawValue == 2 || myMediaPlayer.playbackState.rawValue == 0 {
            on.setTitle("Pause", for: UIControlState.normal)
            myMediaPlayer.play()
        } else if myMediaPlayer.playbackState.rawValue == 1{
            on.setTitle("Play", for: UIControlState.normal)
            myMediaPlayer.pause()
        } else {
            // do nothing
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试异步加载图像

DispatchQueue.global(qos: .background).async {
    myMediaPlayer.nowPlayingItem?.artwork!.image(at: CGSize.init(width: 500, height: 500))
}