简体   繁体   English

在Spritekit中添加声音效果

[英]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. 我正在制作Flappy Bird型游戏,我想在收集硬币时添加声音效果。 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: 后来在我的didMoveToView中:

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

For the second part (in my didMoveToView), the first line keeps showing an error: 对于第二部分(在我的didMoveToView中),第一行继续显示错误:

Call can throw, but it is not marked with 'try' and the error is not handled 调用可以抛出,但它没有标记为'try',并且没有处理错误

How do I fix this? 我该如何解决?

I know you already have marked an answer but if you re read this question or for future readers its easier to use SKActions to play a short 1 time sound. 我知道你已经标记了一个答案,但是如果你读过这个问题,或者对于未来的读者来说,更容易使用SKActions播放短暂的1次声音。

AVFoundation is better used for background music. AVFoundation更适合用于背景音乐。

eg 例如

class GameScene: SKScene {

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

and than when you need to play the sound simply say this 而且当你需要播放声音时,只需说出来

run(coinSound)

Hope this helps 希望这可以帮助

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

This is no longer the way that errors are handled in Swift. 这不再是Swift中处理错误的方式。 You must use the do-try-catch syntax. 您必须使用do-try-catch语法。

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? :

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. 这更接近于您尝试传递nil作为error参数的代码。

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

Swift 3.0+ Swift 3.0+

For the above guard let example from @nhgrif, this Swift 3.0+ way of doing it: 对于上面的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