繁体   English   中英

在Spritekit中添加声音效果

[英]Adding sound effects in Spritekit

我正在制作Flappy Bird型游戏,我想在收集硬币时添加声音效果。 这就是我所拥有的:

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

后来在我的didMoveToView中:

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

对于第二部分(在我的didMoveToView中),第一行继续显示错误:

调用可以抛出,但它没有标记为'try',并且没有处理错误

我该如何解决?

我知道你已经标记了一个答案,但是如果你读过这个问题,或者对于未来的读者来说,更容易使用SKActions播放短暂的1次声音。

AVFoundation更适合用于背景音乐。

例如

class GameScene: SKScene {

     // add as class property so sound is preloaded and always ready
     let coinSound = SKAction.playSoundFileNamed("NAMEOFSOUNDFILE", waitForCompletion: false)
}

而且当你需要播放声音时,只需说出来

run(coinSound)

希望这可以帮助

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

这不再是Swift中处理错误的方式。 您必须使用do-try-catch语法。

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

或者,如果您不打算编写任何错误处理代码,您可以将audioPlayer变量设置为可选,并编写一个可用的try?

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

这更接近于您尝试传递nil作为error参数的代码。

或者,如果发生错误时崩溃是适当的行为,您可以采用以下方法:

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

Swift 3.0+

对于上面的guard let以@nhgrif为例,这个Swift 3.0+方式:

var coinSound = NSURL(fileURLWithPath:Bundle.main.path(forResource: "Super Mario Bros.- Coin Sound Effect", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()

func playCoinSound(){
    guard let soundToPlay = try? AVAudioPlayer(contentsOf: coinSound as URL) else {
        fatalError("Failed to initialize the audio player with asset: \(coinSound)")
    }
    soundToPlay.prepareToPlay()

//  soundToPlay.play() // NO IDEA WHY THIS DOES NOT WORK!!!???

    self.audioPlayer = soundToPlay
    self.audioPlayer.play() // But this does work... please let me know why???
}

playCoinSound()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM