0

I recently started studying Swift and wanted to make a simple DJ sampler to test what I've learned about playing sound when UIButton is pressed.

All 12 buttons are under one @IBAction and differentiated by using tags 1-12

After loading the simulator and pressing one of the buttons, the crash is;

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

Below is the code and the triggered error line in the function. Any help and advice would be greatly appreciated. Thank you for taking a look at the code on this one.

import UIKit
import AVFoundation


class ViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer : AVAudioPlayer!
    var selectedSoundFileName : String = ""
    let soundArray = ["FRESH", "AIR HORN", "BASS", "CANNON", "BREAK", "CHECK IT", "YEAH BOY", "LIKE THIS", "HIT IT", "AHH", "SAH YEAH", "AWW"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func buttonPressed(_ sender: UIButton) {
        
        selectedSoundFileName = soundArray[sender.tag - 1]
        print(selectedSoundFileName)
        playSound()
    }
    
    // all 12 buttons are under one @IBAction and differentiated by using tags 1-12
    func playSound(){
        
        let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL!) 
        } // audioPlayer line above triggers - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value // 
        catch {
            print(error)
        }
        
        audioPlayer.play()
        
    }
    
}
ijb44
  • 11
  • 2
  • 1
    Don't post a picture of your code. Edit your question, paste your code into it, select that code, and tap the "{}" button to format that code. Then indicate which line is failing, and tell us the exact error message. – Duncan C Sep 21 '20 at 23:15
  • @DuncanC thank you for the great feedback and notes below! Made the changes above and working on the code update as well. Thanks again – ijb44 Sep 22 '20 at 00:59

1 Answers1

0

It looks like the offending line is this one:

audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)

I like to call the ! "force unwrap" operator the "crash if nil" operator. If the variable it references contains a nil, it causes a hard crash, with the error message "Unexpectedly found nil while unwrapping an Optional value".

Given that you are using the force-unwrap operator, and getting that exact error message, it seems like a fair bet that your variable soundURL is nil. You should add a print statement above the crashing line that prints the contents of soundURL. Or set a breakpoint at that line and examine the value in that variable. Confirm that the variable is nil. Then figure out why. The likely cause is that the file you are trying to reference doesn't exist at exactly the location you specify, and with the filename you specify.

You might want to print your main bundle's resource path (print(Bundle.main.resourcePath)!). Then run the app from the simulator, copy the path, go to the finder, press command shift "G" paste that path, and examine your app bundle's resource path. Is there a file named <filename>.wav there (where <filename> is your filename? I bet not. (Note that the name needs to match exactly, including the same case.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272