Play local audio file with AVAudioPlayer

♀尐吖头ヾ 提交于 2019-11-29 10:44:40

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!