Search code examples
swiftxcodeswift3xcode8avaudioplayer

AVAudioPlayer is turning nil


Something is wrong with my code but I can't figure out what is wrong. If I compile the code everything is fine, but if I run the code I get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

I've seen lots of the same questions but the answer to those questions is not useful in my case.

import UIKit
import AVFoundation
import AudioToolbox



class ViewController: UIViewController{
   
    var audioPlayer = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath:  Bundle.main.path(forResource: "beep", ofType: "wav")!))
            audioPlayer.prepareToPlay()
            
        } catch{
            print(error)
        }
        
        //standaard klaarmaaklijst
        nummerLabel.text = "\(schijnNummer)"
        nummerCheck()
    }

@IBOutlet weak var nummerLabel: UILabel!
}

I hope someone knows what's wrong with my code.


Solution

  • Swift :

        if let path = Bundle.main.path(forResource: "beep", ofType:"wav") {
            let url = URL(fileURLWithPath: path)
    
            do {
    
                let audioPlayer = try AVAudioPlayer(contentsOf: url)
                audioPlayer.prepareToPlay()
    
            } catch{
                print(error)
            }
        }
    

    Note: Please check if the url is proper and not nil.