我正在制作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'并且未处理错误
我该如何解决这个问题?
答案 0 :(得分:6)
我知道你已经标记了一个答案,但是如果你读过这个问题,或者对于未来的读者来说,更容易使用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)
希望这有帮助
答案 1 :(得分:1)
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()
这更接近于您在为{error}参数传递nil
时尝试的代码。
或者,如果发生错误时崩溃是适当的行为,您可以采用这种方法:
guard let audioPlayer = try? AVAudioPlayer(contentsOfURL: coinSound) else {
fatalError("Failed to initialize the audio player with asset: \(coinSound)")
}
audioPlayer.prepareToPlay()
self.audioPlayer = audioPlayer
答案 2 :(得分:0)
对于@nhgrif的上述guard let
示例,这种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()