swift 无法播放脱机音频

o75abkj4  于 2023-04-28  发布在  Swift
关注(0)|答案(1)|浏览(90)

我有以下代码

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?) {
有人知道我哪里做错了吗?

n53p2ov0

n53p2ov01#

您不必等待状态更改即可开始播放。所以只要在玩家物品的定义之后尝试玩就可以了。

player.seek(to: .zero)    
player.play()

也许苹果文档也会有所帮助-https://developer.apple.com/documentation/avfoundation/media_playback/observing_playback_state
P.S.你不需要为每个新的负载制作一个播放器。您可以替换当前项目。

相关问题