1
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!

Ken White
  • 123,280
  • 14
  • 225
  • 444

1 Answers1

0
  • Try not to implicitly unwrap your player variable.
  • Unwrap the optional url variable using guard let.

Possible solution for solving the issue,

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) {
        guard let url = Bundle.main.url(forResource: soundName, withExtension: "wav") else {
            print("Error: sound file not found")
            return
        }

do {
        player = try AVAudioPlayer(contentsOf: url)
        player?.play()
    } catch let error {
        print("Error: \(error.localizedDescription)")
    }
}
}
  • 1
    Actually, force unwrapping the url is fine in a case like this since it is an expected file from the app bundle. You want it to fail during development if the file isn’t found. – HangarRash Mar 23 '23 at 14:47
  • 1
    Thanks @HangarRash and @yasir! I've updated with your code and now I'm getting the printed error sound file not found. I believe I'm not linking my sound file correctly. Do you know how I can link it? – Amit Tandel Mar 23 '23 at 18:34