swiftxcodeaudioplaysound

Why can't I play sound when a button is pressed?


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

}

Solution

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