Infinite Sound: Cocos2D

“EXC bad access” aren’t annoying things anymore. Here is another story of it. I was playing a sound effect on loop for one specific condition.

When time came to stop the sound, it gave me exc bad access. I had a reference to that memory and inspected the allocated object and seems fine. I was tinkering a lot to get to root of it. Whatever i did, crash was the fruit. It seemed the reference to that chunk of memory was corrupted and embraced the dark side.

loopSound = [[SimpleAudioEngine sharedEngine] soundSourceForFile:@"awesome.wav"];
loopSound.looping = YES;
[loopSound play];

Crash occurred when trying to stop the sound

[loopSound stop];

It was an autoreleased object. When trying to access such memory from different function/different scope other than the one where it was created; could lead to such memory issue. Since it was a sound and was been played by audio engine, so i was under impression that it must be retained. I guess it wasn’t so because every time i access from somewhere outside it gave “exc bad access”.

So i wrote the lines to retain my such sound objects for my purpose. This code is just to imply the concept hence can be much written on more improved way.

CDSoundSource *loopSound = [[SimpleAudioEngine sharedEngine] soundSourceForFile:@"Magnet_Adam.wav"];
[loopSounds addObject:loopSound];
loopSound.looping = YES;
[loopSound play];

I was adding my sounds to mutable array after creation. My array was taking the responsibility to retain my sounds. I could stop them and remove them anytime.

for (CDSoundSource *soundd in loopSounds) {
        [soundd stop];

If want to remove all sounds after been done then simply:

[loopSounds removeAllObjects];

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>