2011-07-04 48 views
3

我使用cocos2d的,系统的粒子,我希望我的英文正确写了这个。 我有问题认识的声音在一定的方式iPhone的麦克风。在iPhone麦克风吹气检测用的Cocos2D

我在我的应用程序不同的部分,在其中的一个我用的麦克风来检测是否有人“吹空气”到话筒。这部分在开始工作正常,但如果你去播放声音的应用程序的其他部分,以后你回到这个区域,并试图炸毁空气,它不会工作。

我debuged的代码,并levelTimeCallback总是工作,即使我没有在这个场景。我不知道发生了什么。我已经不再使用

[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];

任何人都知道我在做什么错了所有的声音? BTW在模拟器中完美工作,但不在iPhone中。

录音机在的OnEnter方法

-(void) onEnter { 
    [super onEnter]; 
    NSURL *url = [NSURL fileURLWithPath:@"/dev/null"]; 

    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys: 
          [NSNumber numberWithFloat: 44100.0],     AVSampleRateKey, 
          [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, 
          [NSNumber numberWithInt: 1],       AVNumberOfChannelsKey, 
          [NSNumber numberWithInt: AVAudioQualityMax],   AVEncoderAudioQualityKey, 
          nil]; 

     NSError *error; 

     recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; 

     if (recorder) { 
      [recorder prepareToRecord]; 
      recorder.meteringEnabled = YES; 
      [recorder record]; 
      levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES]; 
      NSLog(@"I'm in the recorder"); 

     } else 

       NSLog(@"recorder error"); 

}

设置这是levelTimerCallback方法是声音 “选中”

- (void)levelTimerCallback:(NSTimer *)timer { 

[recorder updateMeters]; 
const double ALPHA = 0.05; 
double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0])); 
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults; 

if (lowPassResults > 0.55) 
{ 
    NSLog(@"Mic blow detected"); 

    self.emitter = [[CCParticleExplosion alloc] initWithTotalParticles:5]; 
    [self addChild: emitter z:1];   
    emitter.texture = [[CCTextureCache sharedTextureCache] addImage: @"hoja.png"];  
    emitter.autoRemoveOnFinish = YES; 

} 
NSLog(@"Inside levelTimerCallback");} 

回答

2

最后,读取音频会话菜谱和不同类型的岗位相关的后我找到了解决方案。物权法把这个代码块在INIT方法:

UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord; 
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; 
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory); 
    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride); 
    AudioSessionSetActive(true); 
+0

好的答案...它帮助我... –

3

同样的问题。 有两种方法可以解决这个问题。

1:使用AVAudioPlayer播放音乐或音效。

2:添加#import "CDAudioManager.h"到AppDelegate.m并添加

[CDAudioManager initAsynchronously:kAMM_PlayAndRecord]; 

- (void) applicationDidFinishLaunching:(UIApplication*)application` 

source

+0

嗨@huyleit!谢谢回答!我找到的解决方案是: –

+0

为了在init方法中放置一些代码,我使用解决方案修改了原始帖子。非常感谢您的回答,我将不得不尝试您的解决方案。 –

+0

哇....感谢您的宝贵回答@huyleit ... –

0

如何导入这个代码上面科科斯2DX(C++)。如何在C++中调用此方法?