Play local audio file with AVAudioPlayer

I’m testing my app in simulator.

I’m downloading file and getting it’s local way like this one:
file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

  • CoreAudio AudioTimeStamp.mHostTime clock frequency?
  • Combine two audio files into one in objective c
  • AVAudioPlayer not playing audio in Swift
  • iOS background audio stops when screen is locked
  • Trigger AVAudioPlayer to stop all sounds and play selected except when playing(selected) button is clicked
  • Phonegap mixing audio files
  • Now I want to play this file with AVAudioPlayer but I’m always getting this error:

    file:///
    Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
    

    Code for playing:

    var alertSound = NSURL(fileURLWithPath: "file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3")
            print(alertSound)
    
            var error:NSError?
            do {
                try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
    

    How should I make it playing?

    4 Solutions Collect From Internet About “Play local audio file with AVAudioPlayer”

    Under iOS8, the path that you have saved won’t be valid across launches. The id you see “E5F13797-A6A8-48A1-B3C3-FBC3D7A03151” will change with each launch.

    The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.

    Look at NSFileManager. The method URLForDirectory:inDomain:appropriateForURL:create:error: is what you should use.

    // create the soundFileURL for the word
            let toAppendString = "\(String)" //
            let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
            soundFileURL = documentsDirectory.URLByAppendingPathComponent(toAppendString)
    
        do {
        self.player = try AVAudioPlayer(contentsOfURL: soundFileURL)
            player.prepareToPlay()
            player.volume = 1.0
            player.play()
    
        } catch let error as NSError {
            print(error)
        }
    
                let fileName = ("FILE_NAME.mp3")
            let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
            let soundFileURL = documentsDirectory.URLByAppendingPathComponent(fileName)
            AudioCenter.player.playURL(soundFileURL)