Displaying Artwork for .MP3 file

前端 未结 3 871
星月不相逢
星月不相逢 2020-12-05 08:56

I am trying to currently display the album artwork for a locally stored .MP3 track in an ImageView. Does anyone know how to fetch this artwork in Swift in order to accomplis

3条回答
  •  醉话见心
    2020-12-05 09:24

    edit/update Swift 4 or later:

    import MediaPlayer
    
    
    var nowPlayingInfo: [String: Any] = [:]
    let playerItem = AVPlayerItem(url: url)
    let metadataList = playerItem.asset.metadata
    
    for item in metadataList {
        switch item.commonKey {
        case .commonKeyTitle?:
            nowPlayingInfo[MPMediaItemPropertyTitle] = item.stringValue ?? ""
        case .commonKeyType?:
            nowPlayingInfo[MPMediaItemPropertyGenre] = item.stringValue ?? ""
        case .commonKeyAlbumName?:
            nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = item.stringValue ?? ""
        case .commonKeyArtist?:
            nowPlayingInfo[MPMediaItemPropertyArtist] = item.stringValue ?? ""
        case .commonKeyArtwork?:
            if let data = item.dataValue,
                let image = UIImage(data: data) {
                nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
            }
        case .none: break
        default: break
        }
    }
    

    let audioInfo = MPNowPlayingInfoCenter.default()
    audioInfo.nowPlayingInfo = nowPlayingInfo
    

    Note: You will have to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device. You will also need to set your app Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active:

    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)
    }
    

    enter image description here

提交回复
热议问题