iOS 录音功能的实现

1.初始化录音设置

    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [session setActive:YES error:nil];
    //录音设置
    NSMutableDictionary * recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式
    [recordSetting  setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(HZ)
    [recordSetting setValue:[NSNumber numberWithFloat:4000] forKey:AVSampleRateKey];
    //录音通道数
    [recordSetting setValue:[NSNumber  numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数
    [recordSetting  setValue:[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting  setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey]; 
    //获取沙盒路径 作为存储录音文件的路径
    NSString * strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"path = %@",strUrl);
    //创建url
    NSURL * url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/voice.aac",strUrl]];
    self.urlPlay = url;
    NSError * error ;
    //初始化AVAudioRecorder
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量监测
    self.recorder.meteringEnabled = YES;
    self.recorder.delegate = self;
    if(error){
        NSLog(@"创建录音对象时发生错误,错误信息:%@",error.localizedDescription);
    }

2.开始录音

if([_recorder prepareToRecord]){
        //开始
        [_recorder record];
        NSLog(@"开始录音");
    }

3.录音结束

//获取当前录音时长
    float voiceSize = self.recorder.currentTime;
    
    NSLog(@"录音时长 = %f",voiceSize);
    
    if(voiceSize < 3){
        [self.recorder deleteRecording];
        UIAlertView * altView = [[UIAlertView alloc]initWithTitle:nil
                                                          message:@"时长小于3秒,重新录制" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [altView show];
        
        [self performSelector:@selector(performDismiss:) withObject:altView afterDelay:1.5];
        
    }else if (voiceSize > 60){
        
        [self.recorder deleteRecording];
        UIAlertView * altView = [[UIAlertView alloc]initWithTitle:nil
                                                          message:@"时长大于1分钟,重新录制" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [altView show];
        
        [self performSelector:@selector(performDismiss:) withObject:altView afterDelay:1.5];
    }
    
    [self.recorder stop];

你可能感兴趣的:(iOS 录音功能的实现)