ninefifteen ninefifteen - 1 year ago 226
iOS Question

Playing Motor Sound Effects for iOS SpriteKit Game... AVAudioPlayer vs SKAction vs?

I am developing a driving game using

and am having trouble with engine sound effects.

I want to have two different engine sounds. One for when the throttle button is being pressed and one for when the throttle button is not being pressed. One of the two sounds will be playing constantly while the game is going.

What is the best approach? Should my sound files be extremely short (0.10 seconds or less) and looped or should they be fairly long and just turned on and off? Should I use
to play the sounds or
or something else? I have tried using
but every time I pause and play the player (switching the throttle on or off), the frame rate of the game momentarily drops. Any help is appreciated!

Answer Source

Based on the comment left by LearnCocos2D, I looked into ObjectAL. For those not familiar with ObjectAL, it is designed to be a simple and intuitive interface to OpenAL and AVAudioPlayer. You can download and find more information about it here...

For my audio clip I used 3 to 5 second long .caf audio file of a motor sound. ObjectAL allowed me to continuously loop and vary the pitch of the audio file. By varying the pitch, I could simulate the motor at different speeds.

Below is a sample of the code...

Two member variables or you can set them as properties...

ALBuffer *_buffer;
ALSource *_source;

Method to initialize the motor sound effect...

- (void)initializeSound
    // We'll let OALSimpleAudio deal with the device and context.
    // Since we're not going to use it for playing effects, don't give it any sources.
    [OALSimpleAudio sharedInstance].reservedSources = 0;

    _source = [ALSource source];
    _buffer = [[OpenALManager sharedInstance] bufferFromFile:@"EngineSound.caf"];
    _source.pitch = 0.30;    // Start at low pitch for engine idle.
    [_source play:_buffer loop:YES];

Inside my SKScene's update method I adjust the pitch according to speed.

- (void)update:(CFTimeInterval)currentTime
    CGFloat enginePitch;

    // Code to calculate desired enginePitch value based on vehicle speed.

    _source.pitch = enginePitch;

Because of an alleged bug in SpriteKit, I did have an issue with a gpus_ReturnNotPermittedKillClient EXC_BAD_ACCESS error when closing the app. I found the fix here...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download