//
//  UponAudioRecorder.m
//  audioTest
//
//  Created by 叶湘 on 2018/1/11.
//  Copyright © 2018年 叶湘. All rights reserved.
//

#import "UponAudioRecorder.h"
#import <AVFoundation/AVFoundation.h>


@implementation UponAudioRecorder {
    AVAudioRecorder * _recorder;
    NSURL * _fileURL;
}

- (void)dealloc {
    if (_recorder) {
        if ([_recorder isRecording]) {
            [_recorder stop];
        }
    }
    
    _recorder = nil;
    _fileURL = nil;
}

- (BOOL) startAudioRecorderWithFileUrl:(NSString *)url withSample:(NSInteger)samples {
    if (_recorder != NULL) {
        if ([_recorder isRecording]) {
            [_recorder stop];
        }
        _recorder = NULL;
    }
    
    _fileURL = [NSURL fileURLWithPath:url];
    NSDictionary * recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: samples],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:_fileURL settings:recordSetting error:NULL];
    
    if (_recorder) {
        [_recorder prepareToRecord];
        [_recorder record];
        return YES;
    }
    return NO;
}

- (BOOL) stopAudioRecorder {
    if (_recorder) {
        [_recorder stop];
        _recorder = NULL;
    }
    return YES;
}
@end
