Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sound resource can not be loaded Swift SKAction

I have an app that plays a sound file every time the screen is touched. For some reason, the app will crash every once in a while with the following error:

reason: 'Resource tick.mp3 can not be loaded'

In case you need it, here is how I play the file each time the screen is tapped:

runAction(SKAction.playSoundFileNamed("tick.mp3", waitForCompletion: false))

This does not happen very often, maybe 1 in 10 runs of the app. Most of the time everything works as expected. I wish I knew what I am doing to cause the crash but I have no clue! I am just tapping away seemingly no different than the times when it doesn't crash. Then all of a sudden I get this issue...

like image 553
Reece Kenney Avatar asked Oct 22 '14 22:10

Reece Kenney


2 Answers

If you play the sound via a playSound function, it will work

var soundFile = SKAction.playSoundFileNamed("bark.wav", waitForCompletion: false)
playSound(soundFile)

playSound:

func playSound(soundVariable : SKAction)
{
    runAction(soundVariable)
}
like image 92
Reece Kenney Avatar answered Sep 22 '22 10:09

Reece Kenney


First of all, it looks like that you are using mp3 file to play (short) sound effects. When using mp3 the audio is compressed. In memory, it will have different, bigger size. Also there is a decoding performance penalty (decoding takes CPU time). The most important thing, and the reason why I am talking about mp3 files can be found in docs:

When using hardware-assisted decoding, the device can play only a single instance of one of the supported formats at a time. For example, if you are playing a stereo MP3 sound using the hardware codec, a second simultaneous MP3 sound will use software decoding. Similarly, you cannot simultaneously play an AAC and an ALAC sound using hardware. If the iPod application is playing an AAC or MP3 sound in the background, it has claimed the hardware codec; your application then plays AAC, ALAC, and MP3 audio using software decoding.

As you can see,the problem is that only one mp3 file at a time can be played using hardware. If you play more than one mp3 at a time, they will be decoded with software and that is slow.

So, I would recommend you to use .wav or .caf files to play sound effects. mp3 would be probably good for background music.

About crashing issue:

  • try to use .wav or .caf files instead of .mp3
  • try to hold a strong reference to the SKAction and reuse it as suggested by Reece Kenney.
like image 24
Whirlwind Avatar answered Sep 19 '22 10:09

Whirlwind