swagger swagger - 24 days ago 14
Swift Question

Adding sound effects in Spritekit

I'm making a Flappy Bird-type game, and I want to add a sound effect for when a coin is collected. This is what I have:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

var coinSound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Super Mario Bros.- Coin Sound Effect", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()


Later in my didMoveToView:

audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()


For the second part (in my didMoveToView), the first line keeps showing an error:


Call can throw, but it is not marked with 'try' and the error is not handled


How do I fix this?

Answer
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)

This is no longer the way that errors are handled in Swift. You must use the do-try-catch syntax.

do {
    audioPlayer = try AVAudioPlayer(contentsOfURL: coinSound)
    audioPlayer.prepareToPlay()
}
catch let error {
    // handle error
}

Alternatively, if you don't care to write any error handling code, you can make your audioPlayer variable optional and write a failable try?:

audioPlayer = try? AVAudioPlayer(contentsOfURL: coinSound)
audioPlayer?.prepareToPlay()

This is more closely equivalent to the code you're attempting where you pass nil for the error parameter.

Or if crashing is the appropriate behavior when an error occurs, you could take this approach:

guard let audioPlayer = try? AVAudioPlayer(contentsOfURL: coinSound) else {
    fatalError("Failed to initialize the audio player with asset: \(coinSound)")
}
audioPlayer.prepareToPlay()
self.audioPlayer = audioPlayer
Comments