Swift: Sound returns nil

Question!

I've got this code that plays sound, and it works in different scenes, but when I use it here, as a function, when Enemy collides

func enemy1sound() {

    var enemy1sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("enemy1sound", ofType: "m4a")!)
    println(enemy1sound)

    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: enemy1sound, error: &error)
    audioPlayer.prepareToPlay()
    audioPlayer.play()
}

It throws me this error:

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

Print Screen:

enter image description here

The function is being called from:

var randomEnemySound = Int(arc4random_uniform(4))
if randomEnemySound == 0 {
    enemy1sound()
}
else if randomEnemySound == 1 {
    enemy2sound()
}
else if randomEnemySound == 2 {
    enemy3sound()
}
else if randomEnemySound == 3 {
    enemy4sound()
}

but I don't think that this is the problem.

And here's my question:

What am I doing wrong? Where's that nil? How can I fix it?

Thanks for all help.

By : Betkowski


Answers

I think the error is about using a forced unwrapping operator:

var enemy1sound = NSURL(fileURLWithPath: 
    NSBundle.mainBundle().pathForResource("enemy1sound", ofType: "m4a")!)
                                                                       ^

If in your app logic it's possible and legit for the file to not exist, then I would protect that line of code with an optional binding:

if let path = NSBundle.mainBundle().pathForResource("enemy1sound", ofType: "m4a") {
    let enemy1sound = NSURL(fileURLWithPath:path)
    println(enemy1sound)

    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: enemy1sound, error: 
By : Antonio


This video can help you solving your question :)
By: admin