0

I am trying to play sound with AvPlayer. I am using following method:

func playSound() {
    let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("voiceRecord", ofType: "caf")!)
    do{
        let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }catch {
        print("Error getting the audio file")
    }
}

I am sure I have voiceRecord.caf file in my app's Documents folder. I am getting following error for first line.

fatal error: unexpectedly found nil while unwrapping an Optional value

How to resolve?

Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73
  • This is not a npe question. As i said in my question: I am sure I have voiceRecord.caf file in my app's Documents folder. – Tolgay Toklar Jan 26 '17 at 20:59
  • Your app's `Documents` folder is not the same place as the app's main bundle. – par Jan 26 '17 at 21:04
  • So how to go Documents folder? – Tolgay Toklar Jan 26 '17 at 21:04
  • http://stackoverflow.com/a/14938137/312594 or https://stackoverflow.com/questions/1638834/how-to-check-if-a-file-exists-in-documents-folder?rq=1 – par Jan 26 '17 at 21:05
  • Verify that `NSBundle.mainBundle().pathForResource("voiceRecord", ofType: "caf")` does not return `nil`. If it does, this is a dupe. That is the only place where you are force-unwrapping an optional value. Please read the linked question. – JAL Jan 26 '17 at 21:16

0 Answers0