我正在使用 cocos2d v2 并遇到一个非常奇怪的行为。
我有几个音轨应该一个接一个地作为背景音乐播放。但我注意到当这些曲目在后台播放时,屏幕上的任何更新(渲染)都不起作用。
例如,我在每个新曲目之后添加了一个新的精灵标记,但在所有曲目播放完毕之前屏幕上什么都没有显示。我还尝试使用 CCLABELBMFont 显示曲目#,但在所有曲目播放完毕之前,屏幕上也没有显示任何内容。
这是代码:
NSString *keyString;
CCARRAY_FOREACH([[GameManager sharedGameManager] _musicItems], keyString){
if ([[[GameManager sharedGameManager] _soundEngine] isBackgroundMusicPlaying]) {
int waitCycles = 0;
while (waitCycles < AUDIO_MAX_WAITTIME) {
[NSThread sleepForTimeInterval:0.1f];
if (![[[GameManager sharedGameManager] _soundEngine] isBackgroundMusicPlaying]) {
break;
}
waitCycles += 1;
}
}
//play sound file
CCLOG(@"Playing Sound file: %@", keyString);
[[GameManager sharedGameManager] playBackgroundTrack:keyString];
**EDIT:**
/******** changed to include dispatch: start *********/
dispatch_async(dispatch_get_main_queue(), ^{
CCLOG(@"on main thread");
CCSprite *marker = [CCSprite spriteWithSpriteFrameName:@"marker.png"];
[marker setPosition:ccp(100 * count, 200)];
[self addChild:marker z:100];
});
/***************** end **********************/
}
编辑:这是音频设置的实现
-(void)setupAudioEngine{
if(_hasAudioBeenInitialized){
return; //sound engine already initialized
}
else{
_hasAudioBeenInitialized = YES;
NSOperationQueue *queue = [[NSOperationQueue new] autorelease];
NSInvocationOperation *asyncSetupOperation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(initAudioAsync) object:nil];
[queue addOperation:asyncSetupOperation];
[asyncSetupOperation autorelease];
}
}
-(void)initAudioAsync{
//Initialize audio engine asynchronously
CCLOG(@"Audio Manager Initializing");
_managerSoundState = kAudioManagerInitializing;
//start audio engine
[CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_HIGH];
//Init audio manager asynchronously as it can take a few seconds
//The kAMM_FxPlusMusic mode ensure only this game plays audio
[CDAudioManager initAsynchronously:kAMM_FxPlusMusic];
//wait for audio manager to initialize
while ([CDAudioManager sharedManagerState] != kAMStateInitialised) {
[NSThread sleepForTimeInterval:0.1];
}
CDAudioManager *audioManager = [CDAudioManager sharedManager];
if (audioManager.soundEngine == nil || audioManager.soundEngine.functioning == NO) {
CCLOG(@"COCOS Dension failed to init. No audio will play");
_managerSoundState = kAudioManagerFailed;
}
else{
[audioManager setResignBehavior:kAMRBStopPlay autoHandle:YES];
_soundEngine = [SimpleAudioEngine sharedEngine];
_managerSoundState = kAudioManagerReady;
CCLOG(@"COCOS Dension is ready now");
}
}
有人知道为什么会这样吗?