Reputation: 491
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:
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.
Upvotes: 0
Views: 577
Reputation: 72760
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: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
If however that sound file is supposed to exist, and its absence is an exceptional case, it's ok to leave the forced unwrapping because that makes the error bubble up, although causing a crash. In such case I would look into why it's not found - such as, the file actually doesn't exist, etc.
Upvotes: 1