我有以下代码
func getAudioUrl(book: Book) -> URL? {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Unable to access documents directory")
return nil
}
let fileUrl = documentsDirectory.appendingPathComponent("test-audio-" + String(book.id) + ".mp3")
guard FileManager.default.fileExists(atPath: fileUrl.path) else {
print("File does not exist")
return nil
}
return fileUrl
}
let fileURL = OfflineHandler.sharedInstance.getAudioUrl(book: currentItem as! Book)
if (fileURL != nil) {
let asset = AVAsset(url: fileURL!)
avPlayerItem = AVPlayerItem(asset: asset)
}
NotificationCenter.default.addObserver(self, selector:#selector(self.itemDidFinishPlaying(_:)), name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: avPlayerItem)
audioPlayer = AVPlayer(playerItem: avPlayerItem)
audioPlayer?.volume = 1.0
audioPlayer?.automaticallyWaitsToMinimizeStalling = false
updateCC()
isReadyToPlay = true
audioPlayer?.currentItem?.addObserver(self, forKeyPath: "status", options: ([.new, .initial]), context: nil)
}
当用户没有Internet连接时,我正在尝试播放存储在“文档”文件夹中的音频文件。我得到一个错误,其中“status = unknown”(override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
)
有人知道我哪里做错了吗?
1条答案
按热度按时间n53p2ov01#
您不必等待状态更改即可开始播放。所以只要在玩家物品的定义之后尝试玩就可以了。
也许苹果文档也会有所帮助-https://developer.apple.com/documentation/avfoundation/media_playback/observing_playback_state
P.S.你不需要为每个新的负载制作一个播放器。您可以替换当前项目。