iOS音频开发之音频录制与播放

1.录音

录音使用的对象是AVAudioRecorder对象,其录音步骤分为一下几个步骤:
(1)初始化一个全局会话AVAudioSession,并设置会话种类:[_session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
(2)//激活全局会话:[_session setActive:YES error:nil];
(3)指定音频存储路径
(4)设置录音相关参数并初始化录音器对象AVAudioRecorder
(5)设置录音缓冲并开始录制:[_recoder prepareToRecord], [_recoder record];
其实现代码如下:

///录音/取消/完成
- (void)recordAction:(UIButton *)sender {
    if (sender.tag == 132343 ) {
        //取消 删除录制的音频
        _timeLabel.text = @"00:00:00";
        if (_recordButtons[1].selected) {
            _recordButtons[1].selected = NO;
            [_timer invalidate];
            _timer = nil;
        }
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager  fileExistsAtPath:_filePath]) {
            //删除路径下的录音文件
            BOOL isDeleteSucess = [manager removeItemAtPath:_filePath error:nil];
            if (isDeleteSucess) {
                iToastMsg(@"请重新录制!");
            }
        } else {
            iToastMsg(@"未录制音频!");
        }
    }else if (sender.tag ==132344 ) {
        //录音或者暂停
        sender.selected = ! sender.selected;
        if (sender.selected) {
            iToastMsg(@"开始录音!!!");
            //初始化全局会话
            _session = [AVAudioSession sharedInstance];
            NSError *sessionError;
            //设置会话种类
            [_session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
            //激活全局会话
            if (_session) {
                [_session setActive:YES error:nil];
            }
            //时间戳
            NSDateFormatter *nameforamt = [NSDateFormatter new];
            [nameforamt setDateFormat:kDateFormat_yyyyMdHms];
            NSString *dateStr = [ nameforamt stringFromDate:[NSDate date]];
            //指定音频存储路径
            _filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.wav",dateStr]];
            DLog(@"path = %@",_filePath);
            _recoderUrl = [NSURL fileURLWithPath:_filePath];
            //设置录音参数
            NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                           [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                           [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                           [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                           [NSNumber numberWithInt:AVAudioQualityMax],AVEncoderAudioQualityKey,
                                           nil];
            NSError *initError;
            //初始化录音器
            _recoder = [[AVAudioRecorder alloc] initWithURL:_recoderUrl
                                                   settings:recordSetting
                                                      error:&initError];
            if (_recoder) {
                _recoder.meteringEnabled = YES;
                //开始录音
                [_recoder prepareToRecord];
                [_recoder record];
                __block NSInteger hour = 0;
                __block NSInteger minute = 0;
                //定时器计算录音时长
                _timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                         repeats:YES
                                                           block:^(NSTimer * _Nonnull timer) {
                                                               _seconds ++;
                                                               if (_seconds>60) {
                                                                   minute ++;
                                                                   _seconds = 0;
                                                               }
                                                               if (minute>60) {
                                                                   minute = 0;
                                                                   hour ++;
                                                               }
                                                               NSString *secondstr= [NSString stringWithFormat:@"%@%zd" ,_seconds< 10 ? @"0":@"" ,_seconds];
                                                               NSString *minuteStr= [NSString stringWithFormat:@"%@%zd" ,minute< 10 ? @"0":@"" ,minute];
                                                               NSString *hourStr= [NSString stringWithFormat:@"%@%zd" ,hour< 10 ? @"0":@"" ,hour];
                                                               _timeLabel.text = [NSString stringWithFormat:@"%@:%@:%@",hourStr,minuteStr,secondstr];
                                                           }];
                [[NSRunLoop currentRunLoop]  addTimer:_timer forMode:NSRunLoopCommonModes];
            } else {
                iToastMsg([initError description]);
            }
        } else {
            iToastMsg(@"停止录音!!!");
            if ([_recoder isRecording]) {
                [_recoder stop];
            }
            _totalTimeLabel.text = _timeLabel.text;
            NSFileManager *manager = [NSFileManager defaultManager];
            //计算文件大小
            if ([manager fileExistsAtPath:_filePath]){
                NSString *tipStr = [NSString stringWithFormat:@"录了 %@,文件大小为 %.2fMB",_timeLabel.text,[[manager attributesOfItemAtPath:_filePath error:nil] fileSize]/1024.0/1024.0];
                iToastMsg(tipStr);
            }
            //销毁定时器
            if ([_timer isValid]) {
                [_timer invalidate];
                _timer = nil;
            }
        }
    }
}

2.播放

这里实现播放音频的对象是AVAudioPlayer,值的注意的是这里的AVAudioPlayer音频播放器只能播放本地文件,并且是一次性加载所有的音频数据.这里不做网络流媒体的边下载边实现播放的功能,播放本地的音频文件相对简单,其实现代码如下所示:

    NSError *error;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_filePath] error:&error];
    //设置代理
    _player.delegate = self;
- (void)playOrPause:(UIButton *)sender {
    if (!_filePath.length) {
        iToastMsg(@"未录制音频!");
        return ;
    }
    if ([_timer isValid]) {
        iToastMsg(@"正在录制!");
        return;
    }
    sender.selected = !sender.selected;
    if (sender.selected) {
        //播放
        [_player play];
        //定时器计算播放进度
        [NSTimer scheduledTimerWithTimeInterval:0.01
                                        repeats:YES
                                          block:^(NSTimer * _Nonnull timer) {
                                              NSTimeInterval currentTime = _player.currentTime;
                                              NSInteger hour = currentTime / 3600;
                                              NSInteger minute = currentTime / 60;
                                              NSInteger second = ((NSInteger) currentTime) %60;
                                              NSString *secondstr= [NSString stringWithFormat:@"%@%zd" ,second< 10 ? @"0":@"" ,second];
                                              NSString *minuteStr= [NSString stringWithFormat:@"%@%zd" ,minute< 10 ? @"0":@"" ,minute];
                                              NSString *hourStr= [NSString stringWithFormat:@"%@%zd" ,hour< 10 ? @"0":@"" ,hour];
                                              _playCurrentTimeLabel.text = [NSString stringWithFormat:@"%@:%@:%@",hourStr,minuteStr,secondstr];
                                              float floatValue = currentTime/_seconds;
                                              [_progressView setProgress:floatValue animated:YES];
                                          }];
    } else {
        //暂停
        if ([_player isPlaying]) {
            [_player pause];
        }
    }
}

//清除缓存
- (void)deleteCaches {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *paths = [manager contentsOfDirectoryAtPath:documentPath error:nil];
    //删除音频文件
    for (int i = 0; i < paths.count; i ++) {
        NSString *subPath  = paths[i];
        if ([subPath rangeOfString:@"wav"].length) {
            if ([manager  isDeletableFileAtPath:subPath]) {
                [manager  removeItemAtPath:subPath error:nil];
            }
        }
    }
}
#pragma mark --AVAudioPlayerDelegate
//监听播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    iToastMsg(@"播放完成");
    _playButton.selected = NO;
}

其效果如下所示:


iOS音频开发之音频录制与播放_第1张图片
录音与播放.png

如果您觉着本文对您有帮助的话,请动用您宝贵的双手点个赞!谢谢!
作者---------mrChan1234

你可能感兴趣的:(iOS音频开发之音频录制与播放)