import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
sender.alpha = 0.5
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
sender.alpha = 1.0
}
}
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try!
AVAudioPlayer(contentsOf: url!)
player.play()
}
}
I am creating a piano app, and it runs but when I click on a key it crashes and gives me this error:
Piano_App/ViewController.swift:36: Fatal error: Unexpectedly found nil while unwrapping an Optional value 2023-03-22 19:59:02.100302-0700 Piano App[41562:2080588] Piano_App/ViewController.swift:36: Fatal error: Unexpectedly found nil while unwrapping an Optional value
I'm still learning Swift, so any help is greatly appreciated!