Sprite Kit "hickup" game when playing audio for the first time

In my game with a set of sprites, I use SKAction to play an mp3 file when two sprites collide. While the game is working fine, I noticed a small “hick” in the game when I first played the sound. The full game stops for about half a second. Subsequently, everything is in order, and all subsequent sounds work as they should. I noticed this behavior in the simulator and on my iPhone 5s in the same way.

What can I do to prevent this?

+7
source share
3 answers

I have a similar problem, so here is what I have found so far (I don’t know if it fixes the problem, because I can’t try it right now).

I think the problem is that you did not preload the sound effect. Therefore, when he plays for the first time, it loads and then plays. That's why your game freezes.

The solution is to preload the effect when initializing your scene. You can find an example in this tutorial (scroll down to the part titled "Gratuitous Sound Effects"). This is pretty clear and well explained.

Hope this helps.

+4
source

You can preload the sound file by creating SKAction to play it. (You do not need to run the action, so the sound will not actually play, but the file will be downloaded.)

 SKAction *preload = [SKAction playSoundFileNamed:@"my-sound-effect.caf" waitForCompletion:NO]; 

You do not need to save this instance for later reuse; any similarly initialized SKAction will play instantly at startup.

As a note, and since I found it difficult to find this link, there is a link to a document containing Apple's “Best Practices for iOS Audio” ; Search for "Best." It does not concern pre-loading, but talks about formats and suggests using uncompressed IMA4 or AAC sound, packed into a CAF file. I thought about this because your example played MP3 that may or may not use more processor than you would like to scale.

UPDATE [Aug 2019, iOS12]:

Now, five years later, I understand that the “failure” is not related to file I / O in the audio file, as I always assumed. I can use the System Usage tools (on iPhone 6 running iOS12.4) to prove that every SKAction playSoundFileNamed: will load an audio file from disk, even if it has already been played. However, the main thread freezes for a while. Subsequent readings from the disk, whether this file or another sound file, are relatively fast.

I do not know what caused the initial delay. But it’s important to note that you can cause a “crash” by preloading or losing any sound effect. Obviously, there is no use to preloading all sound effects.

+12
source

To translate Karl Voskuil preset sounds in Swift 2.x :

 let preloadSound = SKAction.playSoundFileNamed("my-sound-effect.caf", waitForCompletion: false) 

after which you can:

 playSound(preloadSound) ... func playSound(soundVariable : SKAction) { runAction(soundVariable) } 
+3
source

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


All Articles