使用Cocos2D检测iPhone Mic中的打击

时间:2011-07-04 13:13:12

标签: audio cocos2d-iphone recorder

我正在使用Cocos2D和系统粒子,我希望我用英语正确地写了这个。 我在用某种方式用iPhone麦克风识别声音时遇到了问题。

我的应用程序中有不同的部分,其中一部分我使用麦克风来检测是否有人“吹气”进麦克风。这个部分在开始时工作正常,但如果你去应用程序的其他部分播放声音,然后你回到这个区域尝试吹气,它将无法正常工作。

我对代码进行了调试,即使我不在这个场景中,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 个答案:

答案 0 :(得分:3)

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

  

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

     

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

 [CDAudioManager initAsynchronously:kAMM_PlayAndRecord];

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

source

答案 1 :(得分:2)

最后,在阅读了音频会话食谱和不同类型的帖子后,我找到了解决方案。 Jus将此代码块放在 init 方法中:

    UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    AudioSessionSetActive(true);
相关问题