AVAudioPlayer.initWithData 抛出异常

AVAudioPlayer.initWithData throwing exception

我正在尝试从远程 URL 播放音频。

let audioData = try! Data.init(contentsOf: URL)
do       
 {
      self.audioPlayer = try AVAudioPlayer.init(data: data) //Throwing error sometimes
      self.audioPlayer?.delegate = self
      self.audioPlayer?.prepareToPlay()     
      self.audioPlayer?.play()

 }
 catch {
          showErrorMessage("An error occurred while trying to extract audio file")

  }

我的服务器上有一个音频列表 url。 对于某些音频 我能够得到 Data 但是在 AVAudioPlayer 的初始化方法中它抛出错误。我无法找到真正的原因。

我可以选择 AVPlayer 但为什么这个问题会导致问题?

只需直接播放 URL 中的音频即可

do
{
  try Manager.player = AVAudioPlayer.init(contentsOf: returnPathAtSelectedIndex(fileName: fileName))
  //Set required delegates and Values

  Manager.player?.delegate = self
  Manager.player?.volume = 1.0
  Manager.player?.prepareToPlay()
  Manager.player?.play()
}
catch
{
  print("Error while playing music: \(error.localizedDescription)")
}

我的播放器

struct Manager 
{
   ///AVAudio Player
    static var player: AVAudioPlayer?
}

我的函数 func returnPathAtSelectedIndex(fileName:String) -> URL Returns a URL.

编辑

作为AVAudioPlayer播放保存到本地的文件。您需要将文件保存到本地而不是

AVAudioPlayer.init(contentsOf:localFileUrl)

将有助于播放文件并且不会产生崩溃。

请将您的代码改成这样,这样您就可以更清楚地知道发生了什么类型的错误:

let audioData = try! Data.init(contentsOf: URL)
do {
   self.audioPlayer = try AVAudioPlayer.init(data: data) //Throwing error sometimes
   self.audioPlayer?.delegate = self
   self.audioPlayer?.prepareToPlay()     
   self.audioPlayer?.play()

}
catch let error {
   print(error.localizedDescription)
   showErrorMessage(error.localizedDescription)

}

我用下面的代码试了一下,效果很好

  let audioData = try! Data.init(contentsOf: url)
    do
    {
        let audioPlayer = try AVAudioPlayer.init(data: audioData) //Throwing error sometimes
        audioPlayer.delegate = self as? AVAudioPlayerDelegate
        audioPlayer.prepareToPlay()
        audioPlayer.play()

    } catch {
        print("An error occurred while trying to extract audio file")
    }

调试本地化描述后出现错误

The operation couldn’t be completed. (OSStatus error 1954115647.)

及以下 link 帮助我解决了我的问题。

Instead of initializing the audio player with the NSData object, save the file to the Documents folder, and then initialized the player with the file URL