我试着用Alamofire下载的数据文件播放mp3。这首歌很好,我可以用AVAudioPlayer(data: Data)播放。如何使用AVPlayer播放相同的数据文件?我找不到如何从数据创建PlayerItem或从数据创建AVAsset。另外,我有歌曲路径的url,但是那个URL在某种程度上不适用于AVPlayer。音乐就是不演奏。
func startSong(withIndex: Int) {
if let item = getItem(atIndex: withIndex) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
let playerItem = item
self.player = AVPlayer(playerItem: playerItem)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func getItem(atIndex: Int) -> AVPlayerItem? {
var item: AVPlayerItem
var url: URL
let song = playlist.getSong(index: atIndex)
if PlaylistsService.sharedService.isFileDownloaded(inPath: SongPath.Offline(id: (song?.getID())!).path()) {
url = URL(fileURLWithPath: SongPath.Offline(id: (song?.getID())!).path())
} else if PlaylistsService.sharedService.isFileDownloaded(inPath: SongPath.Temp(id: (song?.getID())!).path()) {
url = URL(fileURLWithPath: SongPath.Temp(id: (song?.getID())!).path())
} else {
self.downloadSong(song: song!)
url = URL(fileURLWithPath: SongPath.Temp(id: (song?.getID())!).path())
}
item = AVPlayerItem(url: url)
return item
}
@IBAction func playPause(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
print("Play")
self.player.play()
} else {
print("Pause")
self.player.pause()
}
}发布于 2016-11-08 15:30:45
刚刚发现AVPlayerItem不能从指向数据文件的URL创建对象。例如,您需要具有文件扩展名".mp3“的URL。现在,当我将扩展添加到用于下载和播放的路径中时,一切都在正常工作。
https://stackoverflow.com/questions/40489213
复制相似问题