Simple sound effect loop using AudioToolKit
I've created a few sounds for use in my game. I can play them at certain events without issue:
// create sounds
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle();
_soundFileShake = CFBundleCopyResourceURL(mainBundle, CFSTR("shake"), CFSTR("wav"), NULL);
AudioServicesCreateSystemSoundID(_soundFileShake, &_soundIdShake);
// later开发者_运维问答...
AudioServicesPlaySystemSound(_soundIdShake);
The game has a mechanism which allows you to shake the device to activate some functionality. I've got the shaking code done so I get get a "shaking started" and "shaking ended" message to my game. What I need to have happen is start playing "shave.wav" when shaking starts and loop it until it stops. Is there a way to do this with AudioToolbox/AudioServices? How could I do this if not?
Keep track of the "is shaking" state and register a callback for system sound completion with AudioServicesAddSystemSoundCompletion
. Then just start the system sound again whenever it completes AND the device is still being shaken. If the sound is short enough, this will create the desired effect. If you need to ensure the sound stops immediately when the shaking stops, you'll need to use one of the sound APIs that provides more granular control over playback (e.g., Audio Queue Services or AVAudioPlayer
).
精彩评论