首页 文章

来自URL的AVPlayerItem无法播放

提问于
浏览
1

我正试图从我用Alamofire下载的数据文件中播放mp3 . 这首歌很好,我可以用AVAudioPlayer播放(数据:数据) . 我应该如何使用AVPlayer播放相同的数据文件?我找不到如何从Data创建PlayerItem或从Data创建AVAsset . 此外,我有歌曲路径的网址,但该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()
    }
}

1 回答

  • 1

    刚刚发现AVPlayerItem无法从指向数据文件的URL创建对象 . 例如,您需要具有文件扩展名为“.mp3”的URL . 当我将扩展名添加到路径下载和播放时,现在一切正常 .

相关问题