AVPlayer 播放本地歌曲

2019-07-16  本文已影响0人  Jerrydu96

通过Alamofire下载歌曲

let urlString = " ... "

var nameIndex = urlString.lastIndex(of: "=") ?? urlString.endIndex
nameIndex = urlString.index(after: nameIndex)
let name = urlString[nameIndex...]
print("Songname = \(name)")

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("\(name).mp3")
    
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download( urlString, to: destination).response { response in
    
    print(response)
    
    if response.error == nil, let mp3Path = response.destinationURL?.path {
        let playerItem = AVPlayerItem.init(url: URL(fileURLWithPath: mp3Path))
        //a初始化AVPlayer
        //可以随意停止和播放,播放结束后不会释放item
        self.musicPlayer = AVPlayer.init(playerItem: playerItem)
        self.musicPlayer?.play()
    }
}

可以通过以下方法来重置播放的进度

musicPlayer?.currentItem?.seek(to: CMTime.zero)

注册通知来监听播放结束的状态

NotificationCenter.default.addObserver(self, selector: #selector(self.playToEndTime), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)

不要忘记释放监听以避免内存泄漏哦

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.musicPlayer?.currentItem)
上一篇下一篇

猜你喜欢

热点阅读