-1
@IBAction func cowButton(_ sender: UIButton) {
    let soundFileSeleced : String = soundArray[0]
    print(soundFileSeleced)
    playSound()
}
func playSound() {
    let soundURL = Bundle.main.url(forResource: "cowSound", withExtension: ".wav")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    }
    catch {
        print(error)
    }
    audioPlayer.play()
}

I can't get my sound to play. What's wrong with my code? I get the message:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ryan Moye
  • 1
  • 2
  • It means soundURL is nil. Chech the extension or if the name is correctly spelled. And no need of dot (.) When giving file type. – Vimal Dec 09 '17 at 20:48

1 Answers1

0

Check your syntax on the let soundURL line. Pretty sure withExtension shouldn't have the . in it.

Try this?

let soundURL = Bundle.main.url(forResource: "cowSound", withExtension: "wav")

hhanesand
  • 990
  • 11
  • 28