Why is my sound making my game lag in Swift Spritekit?

回眸只為那壹抹淺笑 提交于 2019-12-31 02:26:06

问题


I have this sound effect when my hero node collects a coin and there is this small hiccup in my game. Its not smooth like in other games when there is sound involved when collecting a coin. What am I doing wrong? Heres my code for the sound:

  class GameScene: SKScene, SKPhysicsContactDelegate {

   var coinSound =  NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coin", ofType: "wav")!)
   var coinAudioPlayer = AVAudioPlayer()

   override func didMoveToView(view: SKView) {

   coinAudioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
   coinAudioPlayer.pause()
   }

   if firstBody.categoryBitMask == HeroCategory && secondBody.categoryBitMask == CoinCategory {

   coinAudioPlayer.prepareToPlay()
   coinAudioPlayer.play()
   coinAudioPlayer.currentTime = NSTimeInterval(1.0)
    }

回答1:


Use SKAction.playSoundFileNamed. When you create an SKAction instance ahead of time, it does all the necessary prep to perform the action (in this case, playing a sound) without lag during gameplay. To run the action (play the sound), call runAction on a node — this can be any node, even the scene itself.

Since it doesn't matter which node you use for sound purposes, use whichever is most convenient. For example, if you're just playing a sound you might call runAction on the scene. But if your sound is part of an action group or sequence that, say, animates a sprite, you could make the sound action part of that sequence and play it on the sprite that you're animating.

See SpriteKit Programming Guide for more about actions.


Unrelated Swift tip: use let instead of var for references that won't change. It can help keep you from introducing bugs later, and it probably helps the compiler optimize your code, too.




回答2:


you should not be calling prepareToPlay on the collision, prepareToPlay sets up the sound buffer, do that in your didMoveToView function



来源:https://stackoverflow.com/questions/29585638/why-is-my-sound-making-my-game-lag-in-swift-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!