Sound resource can not be loaded Swift SKAction

2019-06-20 22:25发布

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...

2条回答
在下西门庆
2楼-- · 2019-06-20 23:18

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.
查看更多
可以哭但决不认输i
3楼-- · 2019-06-20 23:25

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)
}
查看更多
登录 后发表回答