Search code examples
iosswiftavaudioplayeravaudiorecorderavplayerlayer

AVAudioPlayer not Play Music again when app run again


I am trying to play save recording files from document directory. The problem is that AVAudioPlayer play music only first time after completing recording. It not play music when i run my app agian. Xcode gives me that error

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)": file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54

On this line

self.audioPlayer = try! AVAudioPlayer(contentsOfURL: filePaths[0])

I also check file it is exist on directory but it not pick it. Any one have any idea how i can resolve it. This is my demo project. Thanks

class FirstViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate{

    var soundRecorder : AVAudioRecorder!
    var audioPlayer : AVAudioPlayer!
    var filePaths : [NSURL]!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func playBt(sender: AnyObject) {
        if filePaths.count > 0 {
            //print(soundRecorder.url)
            print(filePaths[0])
            self.audioPlayer = try! AVAudioPlayer(contentsOfURL: filePaths[0])
            self.audioPlayer.prepareToPlay()
            self.audioPlayer.delegate = self
            self.audioPlayer.play()
        }
    }

}*

Solution

  • The problem with the code is that you are trying to save the URL's Array to the UserDefaults. The container can change anytime, so it is better to save the fileNames in UserDefaults and then create the path to document directory using NSSearchPathForDirectoriesInDomains.