按照SimpleAudioEngine的顺序播放声音
我正在用cocos2d 2构build一个iOS应用程序,并使用SimpleAudioEngine来播放一些效果。
在上一个声音完成后,是否有sorting多个声音的方法?
例如在我的代码中:
[[SimpleAudioEngine sharedEngine] playEffect:@"yay.wav"]; [[SimpleAudioEngine sharedEngine] playEffect:@"youDidIt.wav"];
当这段代码运行时, yay.wav
和youDidIt.wav
会在相同的时间播放。
我想要yay.wav
播放,一旦完成, youDidIt.wav
播放。
如果不是SimpleAudioEngine,AudioToolbox还有其他的方法吗?
谢谢!
== 更新 ==
我想我要用这个方法去使用AVFoundation:
AVPlayerItem *sound1 = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"yay" ofType:@"wav"]]]; AVPlayerItem *sound2 = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"YouDidIt" ofType:@"wav"]]]; AVQueuePlayer *player = [[AVQueuePlayer alloc] initWithItems: [NSArray arrayWithObjects:sound1, sound2, nil]]; [player play];
简单的方法是使用-[CDSoundSource durationInSeconds]
获得曲目持续-[CDSoundSource durationInSeconds]
,然后在适当的延迟之后安排第二个效果播放:
[[SimpleAudioEngine sharedEngine] performSelector:@selector(playEffect:) withObject:@"youDidIt.wav" afterDelay:duration];
获取audio持续时间的更简单的方法是修补SimpleAudioManager并添加一个查询其CDSoundEngine
(一个静态全局)audio持续时间的方法:
- (float)soundDuration { return [_engine bufferDurationInSeconds:_soundId]; }
第二种方法是轮询audio引擎的状态,并等待它停止播放。
alGetSourcei(sourceId, AL_SOURCE_STATE, &state); if (state == AL_PLAYING) { ...
sourceId
是ALuint
返回的playEffect
。
这很简单,用Cocos2D 2.1进行testing:
-
在SimpleAudioEngine.h上创build一个属性durationInSeconds:
@property (readonly) float durationInSeconds;
-
合成它们:
@synthesize durationInSeconds;
-
像这样修改playEffect:
-(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; } }
-
正如你所看到的,我从bufferManager的结果中直接从soundEngine的bufferDurationInSeconds中插入了durationInSeconds的值。
-
现在,只需要询问[SimpleAudioEngine sharedEngine] .durationInSeconds的值,并且您已经获得了该声音的秒数。
-
在这个秒钟之后放置一个计时器,然后播放你的声音的下一个迭代,或将标志置于OFF位置。