自动检测没有声音AVrecorder

时间:2013-03-18 09:59:19

标签: ios objective-c avaudiorecorder avaudiosessiondelegate

我希望在录制时检测声音。如果声音停止2-3秒,则录音应自动停止。

有什么办法吗? 我做了录音: -

NSArray *dirPaths;
        NSString *docsDir;

        dirPaths = NSSearchPathForDirectoriesInDomains(
                                                       NSDocumentDirectory, NSUserDomainMask, YES);
        docsDir = [dirPaths objectAtIndex:0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"ddMMyyyyhh:mm:ss"];

        NSDate *now = [[NSDate alloc] init];
        NSString *dateString = [dateFormatter stringFromDate:now];
        dateString=[NSString stringWithFormat:@"%@.caf",dateString];
        soundFilePath = [docsDir
                                   stringByAppendingPathComponent:dateString];
        NSLog(@"soundFilePath==>%@",soundFilePath);
        NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
        [soundFilePath retain];
        NSDictionary *recordSettings = [NSDictionary
                                        dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:AVAudioQualityMin],
                                        AVEncoderAudioQualityKey,
                                        [NSNumber numberWithInt:16],
                                        AVEncoderBitRateKey,
                                        [NSNumber numberWithInt: 2],
                                        AVNumberOfChannelsKey,
                                        [NSNumber numberWithFloat:44100.0],
                                        AVSampleRateKey,
                                        nil];
        NSError *error = nil;
        recorder = [[AVAudioRecorder alloc]
                    initWithURL:soundFileURL
                    settings:recordSettings
                    error:&error];
        if (error)
        {
            NSLog(@"error: %@", [error localizedDescription]);
        } else {
            [recorder prepareToRecord];
        }
        [recorder record];

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用AVAudioRecorder音频电平测量支持来跟踪音频电平,并在电平低于某个阈值时停止录制。要启用计量 -

[anAVAudioRecorder setMeteringEnabled:YES];

然后你可以定期打电话:

[anAVAudioRecorder updateMeters];
power = [anAVAudioRecorder averagePowerForChannel:0];
if (power > threshold && anAVAudioRecorder.recording==NO)
    [anAVAudioRecorder record];
else if (power < threshold && anAVAudioRecorder.recording==YES)
    [anAVAudioRecorder stop];
  

阈值:给定的浮点表示(以分贝为单位)   音频通道的当前平均功率。返回值为0 dB   表示满量程或最大功率;返回值为-160 dB   表示最小功率(即接近静音)。

     

如果提供给音频播放器的信号超过±满量程,那么   返回值可能超过0(也就是说,它可能会输入正数   范围内)。

[apple docs]