Game lag when playing AVAudioPlayer

I am creating a game in which a user controls a character using a jet pack. When a jet pack crosses a diamond, I add the diamond to their total, and then play the sound. However, the sound pauses the game for a tenth of a second or so and disrupts the flow. This is the code I'm using:

var diamondSound = NSBundle.mainBundle().URLForResource("diamondCollect", withExtension: "wav")! var diamondPlayer = AVAudioPlayer?() class GameScene: SKScene{ override func didMoveToView(view: SKView) { do { diamondPlayer = try AVAudioPlayer(contentsOfURL: diamondSound) guard let player = diamondPlayer else { return } player.prepareToPlay() } catch let error as NSError { print(error.description) } } 

And then:

  override func update(currentTime: CFTimeInterval) { if character.intersectsNode(diamond){ diamondPlayer?.play() addDiamond() diamond.removeFromParent() } } 

I also use the Sprite Kit, if that matters. Any help is much appreciated!

0
source share
1 answer

Usually I prefer to use SKAction.playSoundWithFile in my games, but this one has a limitation, no volume setting. So, with this extension you can solve this disadvantage:

 public extension SKAction { public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction { let nameOnly = (fileName as NSString).stringByDeletingPathExtension let fileExt = (fileName as NSString).pathExtension let soundPath = NSBundle.mainBundle().URLForResource(nameOnly, withExtension: fileExt) var player: AVAudioPlayer! = AVAudioPlayer() do { player = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil) } catch let error as NSError { print(error.description) } player.volume = atVolume let playAction: SKAction = SKAction.runBlock { () -> Void in player.prepareToPlay() player.play() } if(waitForCompletion){ let waitAction = SKAction.waitForDuration(player.duration) let groupAction: SKAction = SKAction.group([playAction, waitAction]) return groupAction } return playAction } } 

Using

 self.runAction(SKAction.playSoundFileNamed("diamondCollect.wav", atVolume:0.5, waitForCompletion: true)) 
0
source

Source: https://habr.com/ru/post/1264745/


All Articles