I have problem with AVAudioPlayer and playing the short sounds in my spritekit game. I have quite dynamic game scene and when the user tap into particular element I want to
About performance, it is preferable to convert your audio files into .Wav instead of .mp3 The processor then hasn't to uncompress the file before to use it.
I think you must simply review who run this action.
If your sprite is involved in other actions, or some context animations, you can try to launch your sound from the SKNode
who host your sprite.
The best way is always to use reasonable mp3 dimensions..
P.S. : Usually I preefer to use this extension to control also the volume:
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.play()
}
if(waitForCompletion){
let waitAction = SKAction.waitForDuration(player.duration)
let groupAction: SKAction = SKAction.group([playAction, waitAction])
return groupAction
}
return playAction
}
}
You are probably getting lag because you are not preloading your sound files and therefore get some lag/delay when creating/playing them. The best practice is to usually preload your audio files at app launch so that they are ready to play immediately.
So for AVPlayers just set them all up at app launch rather than just before playing them. Than when you want to play the music you just play the AVPlayer.
myAVPlayer1.play()
In regards to SKAction.play... its the same issue. You will need to create a reference to your action rather than calling it directly
So in your gameScene above DidMoveToView you create your sound properties
class GameScene: SKScene {
let sound1 = SKAction.playSoundFileNamed("Test", waitForCompletion: false)
....
}
and than in your game at the correct spot you run it
runAction(sound1)
This way there should be no lag because the sound is already preloaded.
Hope this helps