3

I was watching a tutorial on preloading sounds in SpriteKit to avoid the delay and frame rate drop when first playing the sound.This is the way they said to use the AVAudioPlayer to preload the sounds using the prepareToPlay() method:

import AVFoundation

override func didMoveToView(view: SKView) {

    do {
        let sounds = ["sound1", "sound2"]
        for sound in sounds {
              let audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound ofType: "mp3")!))
        audioPlayer.prepareToPlay()
        }
    }
    catch {
    }
}

And then playing the sound using an SKAction like this:

self.runAction(SKAction.playSoundFileNamed("sound1.mp3", waitForCompletetion: false)

How does this actually preload the sounds? Is there some reference to the actual sound file in memory when you do the prepareToPlay() method? It seems like I would have to use the AVAudioPlayer or the audioPlayer variable since that's what I used the prepareToPlay() method on instead of just referencing the sound file from the SKAction.

8
  • Not sure if that is actually true, unless there is some caching going on, documentation would be needed. Jul 11, 2016 at 18:32
  • 2
    To preload audio, Just create SKAudioNodes but do not add them to the scene, or, if you need to use SKActions, save the action as a variable, and use the variable when needed Jul 11, 2016 at 18:33
  • Shouldn't I go ahead and add the SKAudioNode to the scene once I create it? Then use the .play() method to use it instead of adding it to the scene and using .play()? Jul 11, 2016 at 18:50
  • depends on how much you have going on, If you are preloading 100 audio nodes, you do not want all 100 on your scene Jul 11, 2016 at 18:51
  • Good point. I'll plan on adding it to the scene, play the sound, then remove it from the scene once it's finished playing. Jul 11, 2016 at 18:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.