Search code examples
iosswiftavaudioplayernsdatansurl

AVAudioPlayer.initWithData throwing exception


I am trying to play the audio from remote 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")

  }

I have a list of audio url on my server. for some audio I am able to get the Data but in the AVAudioPlayer's init method it is throwing the error. I am not able to get the actual cause for this.

I have the option of AVPlayer but why this thing is causing the issue?


Solution

  • Just directly Play Audio From URL you have as

    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)")
    }
    

    My Player

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

    My function func returnPathAtSelectedIndex(fileName:String) -> URL Returns a URL.

    Edit

    As the AVAudioPlayer plays the file saved into the local. You need to save the file to local and than

    AVAudioPlayer.init(contentsOf:localFileUrl)

    will help to play the file and won't generate the crash.