Search code examples
iosswiftaudioavaudioplayer

How to play downloaded audio file swift


I have 2 variant of audio file, first embedded, second which I download from server.
First varian is work well. But when I get audio file from server is not playing and get error.

I get path:

file:///var/mobile/Containers/Data/Application/24656EA9-6F1F-4C0F-A6FE-5D457908A80D/Documents/Dumont.mp3

And trying to play

func playMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        player = try AVAudioPlayer(contentsOfURL: newURL)
        player!.numberOfLoops = -1
        player!.prepareToPlay()
        player!.play()
    } catch let error as NSError {
        print(error.description)
    }
}

How to play this audio file in swift 2.3?

Platform iOS >8., Swift 2.3


Solution

  • Hey stupid guys who downvote answer for you:

    if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
      let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent("Dumont.mp3")
        do {
            player = try AVAudioPlayer(contentsOfURL: path)
            player!.numberOfLoops = -1
            player!.prepareToPlay()
            player!.play()
          } catch let error as NSError {
             print(error.description)
          }
    

    This code play downloaded song!