-1

This is the code I have written but I am to new to understand how to fix this error. Every time I run the app the build is successful, but then when I go to tap on the button/key, it gives me this error.

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

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func keyAPressed(_ sender: UIButton) {
        playSound()
    }
    func playSound() {
        let url = Bundle.main.url(forResource: "C", withExtension: "wav")
        player = try! AVAudioPlayer (contentsOf: url!)
        player.play()
    }

}
Don Peter
  • 103
  • 1
  • 7

1 Answers1

0

You are getting the error because the url doesn't exist.

Check whether you specified the correct file name and wrap the play function in do block to catch any other errors. The following code worked without any errors.

func playSound() {
    guard let url = Bundle.main.url(forResource: "C", withExtension: "wav") else {
        print("File not found")
        return
    }
    do {
        player = try AVAudioPlayer(contentsOf: url)
        player.play()
    } catch {
        print(error)
    }
    
}
Jithin
  • 913
  • 5
  • 6
  • Now it is just printing file not found file not found, and then when I fixed that problem it wont play any sound – Andrew Mares Aug 10 '20 at 14:38
  • How did you fix that problem and what is the name your audio file? – Jithin Aug 10 '20 at 16:06
  • never mind I didnt fix either problem. thought i did but i didnt. it still only will print file not found and it also will not play any sound – Andrew Mares Aug 10 '20 at 16:13
  • Make sure you have added the audio file named `C.wav` into the project. The error clearly says such a file doesn't exist in your project folder. – Jithin Aug 10 '20 at 17:15