ios录音功能实现

实现功能主要为:按下按钮开始录音,时间条开始计时,松开停止录音,时间条停止计时,滑开手指放弃录音。保存录音文件到本地document文件中。

一、导入头文件和代理

#import 
<AVAudioRecorderDelegate>

二、在.h文件中声明

{
    MBProgressHUD *HUD;
    UILabel *noticeLabel;//提示标签
}

@property (nonatomic,strong) UIView *recordView;//录音界面
@property (nonatomic,strong) UIButton *recordBtn;//录音按钮
@property (nonatomic,strong) UILabel *timeLabel;  //录音计时
@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机
@property (nonatomic,assign) NSInteger countNum;//录音计时(秒)
@property (nonatomic,strong) NSTimer *timer1;  //控制录音时长显示更新
@property (nonatomic,copy) NSString *cafPathStr;

三、正文

在.m文件中添加

#define margin 15
#define kSandboxPathStr [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
#define kCafFileName @"myRecord.caf"
/**
 *存放所有的音乐播放器
 */
static NSMutableDictionary *_musices;
//页面布局
- (void)setupView
{
    CGFloat recordH = SCREEN_HEIGHT * 0.4;
    CGFloat availH = recordH - margin * 4;

    _recordView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - recordH, SCREEN_WIDTH, recordH)];
    _recordView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_recordView];

    CGFloat timeH = availH * 0.2;
    CGFloat btnH = availH * 0.7;
    CGFloat noticeH = availH * 0.1;

    self.timeLabel.frame = CGRectMake(0, margin, SCREEN_WIDTH, timeH);
    self.recordBtn.frame = CGRectMake((SCREEN_WIDTH - btnH)*0.5, CGRectGetMaxY(self.timeLabel.frame) + margin, btnH, btnH);
    self.recordBtn.layer.cornerRadius = self.recordBtn.frame.size.width * 0.5;

    [self.recordBtn.layer setMasksToBounds:YES];
    [self.recordBtn addTarget:self action:@selector(startRecordNotice) forControlEvents:UIControlEventTouchDown];
    [self.recordBtn addTarget:self action:@selector(stopRecordNotice) forControlEvents:UIControlEventTouchUpInside];
    [self.recordBtn addTarget:self action:@selector(cancelRecordNotice) forControlEvents:UIControlEventTouchUpOutside];

    self.closeBtn.frame = CGRectMake(SCREEN_WIDTH - 25, 5, 20, 20);
    [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [_recordView addSubview:self.timeLabel];
    [_recordView addSubview:self.recordBtn];
    [_recordView addSubview:self.closeBtn];

    noticeLabel = [[UILabel alloc]init];
    noticeLabel.frame = CGRectMake(0, recordH - noticeH - margin, SCREEN_WIDTH, noticeH);
    noticeLabel.textAlignment = NSTextAlignmentCenter;
    noticeLabel.textColor = [UIColor lightGrayColor];
    noticeLabel.font = [UIFont systemFontOfSize:14];
    noticeLabel.text = @"按住不放录制语音";
    [_recordView addSubview:noticeLabel];

    self.timeLabel2.text = @"";

    self.cafPathStr = [kSandboxPathStr stringByAppendingPathComponent:kCafFileName];
}

-(UIButton *)closeBtn
{
    if (!_closeBtn) {
        _closeBtn = [[UIButton alloc]init];
        [_closeBtn setBackgroundImage:[UIImage imageNamed:@"infoClose.png"] forState:UIControlStateNormal];
    }
    return _closeBtn;
}

-(UILabel *)timeLabel
{
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc]init];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:42];
        _timeLabel.text = @"00:00";
        _timeLabel.textColor = MF_ColorFromRGB(215, 155, 252);
    }
    return _timeLabel;
}

- (UIButton *)recordBtn
{

    if (!_recordBtn) {
        _recordBtn = [[UIButton alloc]init];
        _recordBtn.backgroundColor = [UIColor clearColor];

        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"record_norm"] forState:UIControlStateNormal];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"record_high"] forState:UIControlStateHighlighted];
//        _recordBtn.userInteractionEnabled = YES;//方便添加长按手势
    }

    return _recordBtn;
}
//点击关闭页面按钮
- (void)closeBtnClick
{
    [self removeFromSuperview];
}
#pragma mark - 录音方法
//改变录音时间
- (void)changeRecordTime
{

    self.countNum += 1;
    NSInteger min = self.countNum/60;
    NSInteger sec = self.countNum - min * 60;
 //   NSInteger sec = self.countNum;

    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",(long)min,(long)sec];

    if (sec == 59) {
        [self stopRecordNotice];
    }
}

- (void)startRecordNotice{
    self.timeLabel2.text = @"";

    [self stopMusicWithUrl:[NSURL URLWithString:self.cafPathStr]];

    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
    }
//    NSLog(@"----------开始录音----------");
    [self deleteOldRecordFile];
//    如果不删掉,会在原文件基础上录制;虽然不会播放原来的声音,但是音频长度会是录制的最大长度。

    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    if (![self.audioRecorder isRecording]){
//    {0--停止、暂停,1-录制中

        [self.audioRecorder record];
//    首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        self.countNum = 0;
        NSTimeInterval timeInterval =1 ;
//    0.1s
        self.timer1 = [NSTimer scheduledTimerWithTimeInterval:timeInterval  target:self selector:@selector(changeRecordTime)  userInfo:nil  repeats:YES];

        [self.timer1 fire];
    }

    noticeLabel.text = @"脱离按钮,松开手指放弃录音";
}

- (void)stopRecordNotice
{
//    NSLog(@"----------结束录音----------");
    [self.audioRecorder stop];
    [self.timer1 invalidate];

//    计算文件大小
    long long fileSize = [self fileSizeAtPath:self.mp3PathStr]/1024.0;
    NSString *fileSizeStr = [NSString stringWithFormat:@"%lld",fileSize];

    self.timeLabel2.text = [NSString stringWithFormat:@"%ld \" %@kb  ",(long)self.countNum,fileSizeStr];
    self.timeLabel.text = @"01:00";

    [self.delegate getRecordData:self.mp3PathStr type:@"2" fileName:kMp3FileName];

    [self removeFromSuperview];
}


- (void)cancelRecordNotice
{
//    NSLog(@"----------取消录音----------");
    [self.audioRecorder stop];
    [self.timer1 invalidate];

    //    计算文件大小
    long long fileSize = [self fileSizeAtPath:self.mp3PathStr]/1024.0;
    NSString *fileSizeStr = [NSString stringWithFormat:@"%lld",fileSize];

    self.timeLabel2.text = [NSString stringWithFormat:@"%ld \" %@kb  ",(long)self.countNum,fileSizeStr];
    self.timeLabel.text = @"00:00";

    noticeLabel.text = @"按住不放录制语音";
}
//删除旧录音缓存
-(void)deleteOldRecordFile{
    NSFileManager* fileManager=[NSFileManager defaultManager];

    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:self.cafPathStr];
    if (!blHave) {
//        NSLog(@"不存在");
        return ;
    }else {
//        NSLog(@"存在");
        BOOL blDele= [fileManager removeItemAtPath:self.cafPathStr error:nil];
        if (blDele) {
//            NSLog(@"删除成功");
        }else {
//            NSLog(@"删除失败");
        }
    }
}
#pragma mark -  Getter
/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url=[NSURL URLWithString:self.cafPathStr];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;

        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误,错误信息:%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{
    //LinearPCM 是iOS的一种无损编码格式,但是体积较为庞大
    //录音设置
    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
    //录音格式 无法使用
    [recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采样率
    [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];//44100.0
    //通道数
    [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //线性采样位数
    //[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

    return recordSettings;
}
/**
 *停止播放音乐文件
 */
- (void)stopMusicWithUrl:(NSURL *)fileUrl{
    if (!fileUrl) return;//如果没有传入文件名,那么就直接返回

    //1.取出对应的播放器
    AVAudioPlayer *player=[self musices][fileUrl];

    //2.停止
    if ([player isPlaying]) {
        [player stop];
//        NSLog(@"播放结束:%@--------",fileUrl);
    }

    if ([[self musices].allKeys containsObject:fileUrl]) {
        [[self musices] removeObjectForKey:fileUrl];
    }
}
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*)filePath{

    NSFileManager* manager = [NSFileManager defaultManager];

    if ([manager fileExistsAtPath:filePath]){

        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

    }else{
        NSLog(@"计算文件大小:文件不存在");
    }

    return 0;
}

PS:ios音频播放实现http://blog.csdn.net/fantasy_jun/article/details/77895525

你可能感兴趣的:(音频)