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()
}
}