Playing sounds in sequence with SimpleAudioEngine

自作多情 提交于 2019-12-04 11:42:23

The easy way would be getting the track duration using -[CDSoundSource durationInSeconds] and then schedule the second effect playing after a proper delay:

[[SimpleAudioEngine sharedEngine] performSelector:@selector(playEffect:) withObject:@"youDidIt.wav" afterDelay:duration];

An easier way to get the audio duration would be patching SimpleAudioManager and add a method that queries its CDSoundEngine (a static global) for the audio duration:

- (float)soundDuration {
    return [_engine bufferDurationInSeconds:_soundId];
}

The second approach would be polling on the status of the audio engine and wait for it to stop playing.

    alGetSourcei(sourceId, AL_SOURCE_STATE, &state);
    if (state == AL_PLAYING) {
      ...

The sourceId is the ALuint returned by playEffect.

Julio César Fernández Muñoz

It's simple, tested with Cocos2D 2.1:

  1. Creates a property durationInSeconds on SimpleAudioEngine.h :

    @property (readonly) float durationInSeconds;
    
  2. Synthesize them :

    @synthesize durationInSeconds;
    
  3. Modify playEffect like this :

    -(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain {
        int soundId = [bufferManager bufferForFile:filePath create:YES];
        if (soundId != kCDNoBuffer) {
            durationInSeconds = [soundEngine bufferDurationInSeconds:soundId];
            return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:false];
        } else {
            return CD_MUTE;
        }
    }
    
  4. As you can see, I inserted durationInSeconds value directly from soundEngine bufferDurationInSeconds from the result of bufferManager.

  5. Now, only ask for the value [SimpleAudioEngine sharedEngine].durationInSeconds and you've got the float duration in seconds of this sound.

  6. Put a timer this seconds and after this, play the next iteration of your sound or put the flag OFF or something.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!