IBTAudioRecorder.m 13.1 KB
Newer Older
mei's avatar
mei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
//
//  IBTAudioRecorder.m
//  XFFruit
//
//  Created by Xummer on 4/17/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "IBTAudioRecorder.h"
#import "IBTAudioController.h"
#import "IBTCommon.h"

@import AVFoundation;
@import AudioToolbox;

#define kRecordersFileExists        @"Audios"
#define AUDIO_SAMPLE_RATE           22050.0   // 44100.0 : 44100 Hz

@interface IBTAudioRecorder ()
<
    AVAudioRecorderDelegate
>
{
    NSTimer *recordTimer;
    UInt32 m_eRecordAudioType;
}

@property (nonatomic, strong) AVAudioRecorder *m_audioRecorder;
@property (nonatomic, strong) NSString *m_nsRecorderingPath;
@property (nonatomic) BOOL m_bDeletedRecording;

- (NSDictionary *)recordingSettings;
//- (NSDictionary *)recordingSettingsWithAudioFormat:(NSNumber*)format;
+ (NSString*)archivePath:(NSString*)path;
+ (NSString *)globallyUniqueString;
- (void)startReceivedRecordingCallBackTimer;
@end


@implementation IBTAudioRecorder

- (void)dealloc
{
    self.m_audioRecorder = nil;
    self.m_nsRecorderingPath = nil;
    self.finishRecordingBlock = NULL;
    self.receivedRecordingBlock = NULL;
    self.encodeErrorRecordingBlock = NULL;
}

- (id)init
{
    self = [super init];
    if (self) {
        /*
         ------- (支持)
         kAudioFormatMPEG4AAC       acc     'aac '      .m4a
         kAudioFormatAppleLossless  alac    'alac'
         kAudioFormatULaw           ulaw    'ulaw'
         kAudioFormatALaw           alaw    'alaw'
         kAudioFormatiLBC           ilbc    'ilbc'
         kAudioFormatDVIIntelIMA    ima4    0x6D730011
         kAudioFormatLinearPCM      lpcm    'lpcm'
         
         ------- (不支持)
         kAudioFormatMPEGLayer3 mp3 .mp3
         */
        m_eRecordAudioType = kAudioFormatMPEG4AAC;
    }
    return self;
}

+ (void)checkMicrophonePermissionAndRunAction:(void (^)(void))action {
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession requestRecordPermission:^(BOOL granted) {
            if (granted) {
                // Microphone enabled code
                if (action) {
                    action();
                }
            }
            else {
                // Microphone disabled code
                
                // We're in a background thread here, so jump to main thread to do UI work.
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[[UIAlertView alloc] initWithTitle:@"Microphone Access Denied"
                                                message:@"This app requires access to your device's Microphone.\n\nPlease enable Microphone access for this app in Settings / Privacy / Microphone"
                                               delegate:nil
                                      cancelButtonTitle:@"Dismiss"
                                      otherButtonTitles:nil] show];
                });
            }
        }];
    }
    else {
        if (action) {
            action();
        }
    }
}


- (NSString*)recorderingPath
{
    return _m_nsRecorderingPath;
}

- (BOOL)m_bIsRecording
{
    return _m_audioRecorder.recording;
}

- (BOOL)startRecord
{
    return [self startRecordForDuration:0];
}

- (BOOL)startRecordForDuration: (NSTimeInterval) duration
{
    if (!_m_audioRecorder.recording) {
        [[IBTAudioController sharedController] activate];
        [[IBTAudioController sharedController] switchToPlayAndRecordMode];
        
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        
        CLog(@"AVAudioRecorder category %@",[audioSession category] );
        if ([[audioSession category] isEqualToString:AVAudioSessionCategoryPlayAndRecord] || [[audioSession category] isEqualToString:AVAudioSessionCategoryRecord] )
        {
            if ([audioSession isInputAvailable]) {
                
                NSError * error = NULL;
                NSString *fileExists = [[self class] archivePath:kRecordersFileExists];
                if (![[NSFileManager defaultManager] fileExistsAtPath:fileExists]) {
                    [[NSFileManager defaultManager] createDirectoryAtPath:fileExists withIntermediateDirectories:YES attributes:nil error:&error];
                }
                
                
                if (!error) {
                    
                    NSString *ext = [[self class] pathExtensionForAudioType:m_eRecordAudioType];
                    NSString *fileFullName = [[self class] globallyUniqueString];
                    fileFullName = [fileFullName stringByAppendingPathExtension:ext];
                    NSString *fullPath = [fileExists stringByAppendingPathComponent:fileFullName];
                    
                    NSDictionary *recordingSettings = [self recordingSettings];
                    
                    
                    NSURL *fullPathURL = [NSURL fileURLWithPath:fullPath];
                    
                    AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:fullPathURL settings:recordingSettings error:&error];
                    self.m_audioRecorder = recorder;
                    
                    _m_audioRecorder.delegate = self;
                    _m_audioRecorder.meteringEnabled = YES;
                    
                    if (!error) {
                        if ([_m_audioRecorder prepareToRecord]) {
                            
                            self.m_nsRecorderingPath = fullPath;
                            _m_bDeletedRecording = NO;
                            
                            [self startReceivedRecordingCallBackTimer];
                            if (duration < 0.001) {
                                return [_m_audioRecorder record];
                            }
                            else {
                                return [_m_audioRecorder recordForDuration:duration];
                            }
                        }
                        else CLog(@"AVAudioRecorder prepareToRecord failure.");
                    }
                    else {
                        CLog(@"AVAudioRecorder alloc failure.Error: %@", [error description]);
                    }
                }
                else{
                    CLog(@"AVAudioRecorder createDirectoryAtPath failure.Error: %@", [error description]);
                }
                
            }
            else CLog(@"Audio input hardware not available.");
        }
        else CLog(@"AudioSession  not allowed to record.");
    }
    else CLog(@"AVAudioRecorder  already in recording.");
    
    return NO;
}

- (void)stopRecord
{
    double delayInSeconds = 0.1; //0629 0.1
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(recordTimer){
            [recordTimer invalidate];
            recordTimer = nil;
        }
        if (_m_audioRecorder.recording) {
            [_m_audioRecorder stop];
            [[IBTAudioController sharedController] deactivate];
        }
        else CLog(@"AVAudioRecorder  in  not in recording.");
    });
}


- (void)stopAndDeleteRecord
{
    double delayInSeconds = 0.1; //0.1
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(recordTimer)
        {
            [recordTimer invalidate];
            recordTimer = nil;
        }
        
        if (_m_audioRecorder.recording) {
            [_m_audioRecorder stop];
        }
        if (!_m_bDeletedRecording) {
            _m_bDeletedRecording = [_m_audioRecorder deleteRecording];
        }
    });
}

- (void)stopAndDeleteAllRecords
{
    double delayInSeconds = 0.1; //0.1
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(recordTimer)
        {
            [recordTimer invalidate];
            recordTimer = nil;
        }
        
        if (_m_audioRecorder.recording) {
            [_m_audioRecorder stop];
        }
        if (!_m_bDeletedRecording) {
            _m_bDeletedRecording = [_m_audioRecorder deleteRecording];
        }
        
        NSString *fileExists = [[self class] archivePath:kRecordersFileExists];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileExists]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:fileExists
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:nil];
        }
    });
}

#pragma mark
#pragma mark AVAudioRecorderDelegate


- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    if(recordTimer) {
        [recordTimer invalidate];
        recordTimer = nil;
    }
    
    if (_finishRecordingBlock) {
        _finishRecordingBlock(self,flag);
    }
    
    [[IBTAudioController sharedController] deactivate];
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    if(recordTimer) {
        [recordTimer invalidate];
        recordTimer = nil;
    }
    if (_encodeErrorRecordingBlock) {
        _encodeErrorRecordingBlock(self,error);
    }
    
    [[IBTAudioController sharedController] deactivate];
}

- (void)audioRecorderReceivedRecordingCallBack:(NSTimer*)timer
{
    if (_receivedRecordingBlock) {
        if (_m_audioRecorder.recording) {
            [_m_audioRecorder updateMeters];
            CLog(@"%f", [_m_audioRecorder peakPowerForChannel:0]);
            float peakPower = pow(10, (0.05 * [_m_audioRecorder peakPowerForChannel:0]));
            float averagePower = pow(10, (0.05 * [_m_audioRecorder averagePowerForChannel:0]));
            float currentTime = _m_audioRecorder.currentTime;
            _receivedRecordingBlock(self,peakPower,averagePower,currentTime);
        }
    }
}




#pragma mark
#pragma mark Private


- (void)startReceivedRecordingCallBackTimer{
    if(recordTimer) {
        [recordTimer invalidate];
        recordTimer = nil;
    }
    recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                   target:self
                                                 selector:@selector(audioRecorderReceivedRecordingCallBack:)
                                                 userInfo:nil
                                                  repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:recordTimer forMode:NSDefaultRunLoopMode];
    
}

- (NSDictionary *)recordingSettings
{
#if  TARGET_IPHONE_SIMULATOR
    return [NSDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
            [NSNumber numberWithFloat:AUDIO_SAMPLE_RATE], AVSampleRateKey,
            [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
            [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
            [NSNumber numberWithInt:AVAudioQualityMax],AVEncoderAudioQualityKey,
            [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
            [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey, nil];
    
#else
    return @{
             AVFormatIDKey :            @(m_eRecordAudioType),      //ID
             AVSampleRateKey :          @(AUDIO_SAMPLE_RATE),       //采样率
             AVNumberOfChannelsKey :    @(1),                       //通道数
             AVLinearPCMBitDepthKey :   @(8),                       //采样位数
             AVLinearPCMIsBigEndianKey :@(NO),
             AVLinearPCMIsFloatKey :    @(NO),
             //             AVEncoderBitRateKey :      @(96),                      //比特率  16bit - 96db
             AVEncoderAudioQualityKey : @(AVAudioQualityLow),
             };
    
    //    return [NSDictionary dictionaryWithObjectsAndKeys:
    //            [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,//ID
    //            [NSNumber numberWithFloat:AUDIO_SAMPLE_RATE], AVSampleRateKey,//采样率
    //            [NSNumber numberWithInt:2], AVNumberOfChannelsKey,//通道数
    //            [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,//采样位数
    //            [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
    //            [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
    //
    ////            [NSNumber numberWithInt:96], AVEncoderBitRateKey,
    ////            [NSNumber numberWithInt:AVAudioQualityLow],AVEncoderAudioQualityKey,
    //
    //            nil];
    //    //24000.0  1 8 96
#endif
}

+ (NSString *)pathExtensionForAudioType:(UInt32)type {
    
    switch (type) {
        case kAudioFormatMPEG4AAC:
            return @"m4a";
            break;
        default:
            return @"caf";
            break;
    }
}

+ (NSString *)archivePath:(NSString*)path {
    NSString *filePath = [IBTCommon archivePathForCurrentUser];
    return [filePath stringByAppendingPathComponent:path];
}


+ (NSString *)globallyUniqueString {
    return [[NSProcessInfo processInfo] globallyUniqueString];
}

+ (NSString *)recordFilePath {
    return [[self class] archivePath:kRecordersFileExists];
}

@end