如何给 SpriteKit 添加背景音乐?

How do you add background music to SpriteKit?

我试过这样做:

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()

我将此代码放在 didMoveToView 函数中,并且我的代码顶部有 import AVFoundation。我收到错误: Call can throw, but it is not marked with 'try' and the error is not handled.

提前致谢!

在Swift 2中,NSErrorPointer类型的参数被省略,可以在catch块中捕获,如下所示:

do 
{
    let player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
} 
catch let error as NSError
{
    print(error.description)
}

附录:

最好将您的 AVAudioPlayer 声明为 ivar;否则,它可能会被释放,因此音乐将无法播放:

class yourViewController: UIViewController 
{
    var player : AVAudioPlayer!

....

因此,鉴于此,我们对上述 try-catch:

做了一个小改动
do 
{
    player = try AVAudioPlayer(contentsOfURL: soundFileURL, fileTypeHint: nil)
} 
catch let error as NSError
{
    print(error.description)
}

编辑:

你原本拥有的:

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()

特此在Swift2中加入catch子句:

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()

假设您的 class 是 SKScene 的子class:

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
    }
}

(Xcode 8 和 Swift 3)

使用 SpriteKit 这非常简单。您使用声音文件创建一个 SKAudioNote,然后将其作为子项附加到您的场景。默认会循环:

override func didMove(to view: SKView) {
    let backgroundSound = SKAudioNode(fileNamed: "bg.mp3")
    self.addChild(backgroundSound)
}

如果您想在某个时候停止背景音乐,您可以使用内置方法:

    backgroundSound.run(SKAction.stop())

或者您可能想在停止后再次播放声音:

    backgroundSound.run(SKAction.play())

SpriteKit 使这变得非常简单。希望对你有帮助。