In Swift 2, the parameter of type NSErrorPointer
is left out and can be caught within catch
block as follows:
do
{
let player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
}
catch let error as NSError
{
print(error.description)
}
Addendum:
It is better to declare your AVAudioPlayer
as an ivar; otherwise, it could be released and thus the music won't play:
class yourViewController: UIViewController
{
var player : AVAudioPlayer!
....
So, given that, we make a minor change to the aforementioned try-catch
:
do
{
player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
}
catch let error as NSError
{
print(error.description)
}
Edit:
What you originally have:
let soundFilePath = NSBundle.mainBundle().pathForResource("GL006_SNES_Victory_loop.aif", ofType: "GL006_SNES_Victory_loop.aif")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
let player = AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
player.numberOfLoops = -1 //infinite
player.play()
Hereby adding the catch
clause in Swift 2:
let soundFilePath = NSBundle.mainBundle().pathForResource("GL006_SNES_Victory_loop.aif", ofType: "GL006_SNES_Victory_loop.aif")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
do
{
player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
}
catch let error as NSError
{
print(error.description)
}
player.numberOfLoops = -1 //infinite
player.play()
Assuming your class is a subclass of SKScene
:
class yourGameScene: SKScene
{
//declare your AVAudioPlayer ivar
var player : AVAudioPlayer!
//Here is your didMoveToView function
override func didMoveToView(view: SKView)
{
let soundFilePath = NSBundle.mainBundle().pathForResource("GL006_SNES_Victory_loop.aif", ofType: "GL006_SNES_Victory_loop.aif")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
do
{
player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
}
catch let error as NSError
{
print(error.description)
}
player.numberOfLoops = -1 //infinite
player.play()
//The rest of your other codes
}
}