• iOS实现录音功能


    https://www.jianshu.com/p/fb7dfb033989

    ps:文章内容的代码部分,由于不便暴露业务逻辑,可能会有部分删减,但是主体功能基本保留

    背景

    这段时间应公司业务需求,要在项目中添加录音功能,要求订单(具体是什么订单,不便透露)全程实时录音并转码存储,订单完成之后,上传至服务器保存。

    调研过程

    • 音频文件的相关知识
    • 使用系统提供的API调用录音功能
    • 音频文件如何优化、压缩、存储
    • 影响正常使用录音功能的因素

    踩坑过程

    音频文件的相关知识

    • 文件格式(不同的文件格式,可保存不同的编码格式的文件)
      • wav:
        特点:音质最好的格式,对应PCM编码
        适用:多媒体开发,保存音乐和音效素材
      • mp3:
        特点:音质好,压缩比比较高,被大量软件和硬件支持
        适用:适合用于比较高要求的音乐欣赏
      • caf:
        特点:适用于几乎iOS中所有的编码格式

    • 编码格式
      • PCM
        PCM:脉冲编码调制,是一种非压缩音频数字化技术,是一种未压缩的原音重现,数字模式下,音频的初始化信号是PCM
      • MP3
      • AAC
        AAC:其实是“高级音频编码(advanced audio coding)”的缩写,他是被设计用来取代MPC格式的。
      • HE-AAC
        HE-AAC是AAC的一个超集,这个“High efficiency”,HE-AAC是专门为低比特率所优化的一种音频编码格式。
      • AMR
        AMR全称是“Adaptive Multi-Rate”,它也是另一个专门为“说话(speech)”所优化的编码格式,也是适合低比特率环境下采用。
      • ALAC
        它全称是“Apple Lossless”,这是一种没有任何质量损失的音频编码方式,也就是我们说的无损压缩。
      • IMA4
        IMA4:这是一个在16-bit音频文件下按照4:1的压缩比来进行压缩的格式。

    • 影响音频文件大小的因素
      • 采样频率
        采样频率是指单位时间内的采样次数。采样频率越大,采样点之间的间隔就越小,数字化后得到的声音就越逼真,但相应的数据量就越大。
      • 采样位数
        采样位数是记录每次采样值数值大小的位数。采样位数通常有8bits或16bits两种,采样位数越大,所能记录声音的变化度就越细腻,相应的数据量就越大。
      • 声道数
        声道数是指处理的声音是单声道还是立体声。单声道在声音处理过程中只有单数据流,而立体声则需要左、右声道的两个数据流。显然,立体声的效果要好,但相应的数据量要比单声道的数据量加倍。
      • 时长
    • 计算
      数据量(字节/秒)=(采样频率(Hz)× 采样位数(bit)× 声道数)/ 8
      总大小=数据量 x 时长(秒)

    使用系统提供的API调用录音功能

    • 申请访问权限,在plist文件中加入
      <key>NSMicrophoneUsageDescription</key> <string>App需要您的同意,才能访问麦克风</string>

    • 导入头文件
      #import <AVFoundation/AVFoundation.h>

    • 设置AVAudioSession请参照iOS音频掌柜

        - (void)prepareRecord:(void(^)(BOOL granted))completeHandler {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *error;
        NSLog(@"Error creating session: %@", [error description]);
        //设置为录音和语音播放模式,支持边录音边使用扬声器,与其他应用同时使用麦克风和扬声器
        [session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions: AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers error:&error];
        NSLog(@"Error creating session: %@", [error description]);
        [session setActive:YES error:nil];
        //判断是否授权录音
        [session requestRecordPermission:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completeHandler(granted);
            });
        }];
    }
    
    • 录音设置
    - (NSDictionary *)audioSetting {
        static NSMutableDictionary *setting = nil;
        if (setting == nil) {
            setting = [NSMutableDictionary dictionary];
            setting[AVFormatIDKey] = @(kAudioFormatLinearPCM);
            //#define AVSampleRate 8000
            setting[AVSampleRateKey] = @(AVSampleRate);
            //由于需要压缩为MP3格式,所以此处必须为双声道
            setting[AVNumberOfChannelsKey] = @(2);
            setting[AVLinearPCMBitDepthKey] = @(16);
            setting[AVEncoderAudioQualityKey] = @(AVAudioQualityMin);
        }
        return setting;
    }
    
    • 文件缓存目录
    //获取缓存文件的根目录
    - (NSString *)recordCacheDirectory {
        static NSString *directory = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString *cacheDir = [docDir stringByAppendingPathComponent:@"缓存文件夹名字"];
            NSFileManager *fm = [NSFileManager defaultManager];
            BOOL isDir = NO;
            BOOL existed = [fm fileExistsAtPath:cacheDir isDirectory:&isDir];
            if (!(isDir && existed)) {
                [fm createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:nil];
            }
            directory = cacheDir;
        });
        return directory;
    }
    
    //录音文件的缓存路径
    - (NSString *)recordFilePath {
        static NSString *path = nil;
        if (path == nil) {
            path = [[self recordCacheDirectory] stringByAppendingPathComponent:"录音文件名称"];
        }
        return path;
    }
    
    • 开始录音
    //开始录音
    - (void)startRecord {
        [self prepareRecord:^(BOOL granted) {
            if (granted) {
                [self _startRecord];
            }else {
                //进行鉴权申请等操作
            }
        }];
    }
    
    - (void)_startRecord {
        NSDictionary *setting = [self audioSetting];
        NSString *path = [self recordFilePath];
        NSURL *url = [NSURL URLWithString:path];
        NSError *error = nil;
        self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        if (error) {
            NSLog(@"创建录音机时发生错误,信息:%@",error.localizedDescription);
        }else {
            self.audioRecorder.delegate = self;
            self.audioRecorder.meteringEnabled = YES;
            [self.audioRecorder prepareToRecord];
            [self.audioRecorder record];
            NSLog(@"录音开始");
        }
    }
    

    音频文件如何优化、压缩、存储

    • 优化

    鉴于项目中对音频的品质要求不是太高,所以要求最终上传的音频文件尽可能小(经协商使用最终保存的文件格式为mp3,其实amr更好),所以我们所使用的音频采样率8000
    setting[AVEncoderAudioQualityKey] = @(AVAudioQualityMin);
    采样位数16(如果为8的话,最终转码的mp3的语音会严重失真)
    setting[AVLinearPCMBitDepthKey] = @(16);

    • 压缩

    最终保存的文件为mp3,所以需要将caf格式的音频压缩为mp3格式,这部分内容请参照Lame开源库
    下面贴一部分实现代码,可能与上述Lame开源库文章中有所不同

    //接上面的_startRecord方法
    - (void)_startRecord {
        NSDictionary *setting = [self audioSetting];
        NSString *path = [self recordFilePath];
        NSURL *url = [NSURL URLWithString:path];
        NSError *error = nil;
        self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        if (error) {
            NSLog(@"创建录音机时发生错误,信息:%@",error.localizedDescription);
        }else {
            self.audioRecorder.delegate = self;
            self.audioRecorder.meteringEnabled = YES;
            [self.audioRecorder prepareToRecord];
            [self.audioRecorder record];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [self conventToMp3];
            });
            NSLog(@"录音开始");
        }
    }
    
    - (void)conventToMp3 {
        NSString *cafPath = [self recordFilePath];
        NSString *mp3Path = @"目标文件路径";
        @try {
            int read, write;
            FILE *pcm = fopen([cafPath cStringUsingEncoding:NSASCIIStringEncoding], "rb");
            fseek(pcm, 4*1024, SEEK_CUR);
            FILE *mp3 = fopen([mp3Path cStringUsingEncoding:NSASCIIStringEncoding], "wb");
            
            const int PCM_SIZE = 8192;
            const int MP3_SIZE = 8192;
            short int pcm_buffer[PCM_SIZE*2];
            unsigned char mp3_buffer[MP3_SIZE];
            
            lame_t lame = lame_init();
            lame_set_in_samplerate(lame, AVSampleRate);
            lame_set_out_samplerate(lame, AVSampleRate);
            lame_set_num_channels(lame, 1);
            lame_set_mode(lame, 1);
            lame_set_brate(lame, 16);
            lame_set_quality(lame, 7);
            lame_set_VBR(lame, vbr_default);
            lame_init_params(lame);
            
            long currentPosition;
            do {
                currentPosition = ftell(pcm); //文件读到当前位置
                long startPosition = ftell(pcm); //起始点
                fseek(pcm, 0, SEEK_END); //将文件指针指向结束为止
                long endPosition = ftell(pcm); //结束点
                long length = endPosition - startPosition; //获取文件长度
                fseek(pcm, currentPosition, SEEK_SET); //再将文件指针复位
                if (length > PCM_SIZE * 2 * sizeof(short int)) {
                    read = (int)fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
                    if (read == 0) write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                    else write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                    fwrite(mp3_buffer, write, 1, mp3);
                    NSLog(@"转码中...start:%ld,end:%ld",startPosition, endPosition);
                }else {
                    [NSThread sleepForTimeInterval:0.2];
                }
            } while (self.isRecording);
            lame_close(lame);
            fclose(mp3);
            fclose(pcm);
        }
        @catch (NSException *exception) {
            NSLog(@"%@",[exception description]);
            dispatch_async(dispatch_get_main_queue(), ^{
               // do something
            });
        }
        @finally {
            dispatch_async(dispatch_get_main_queue(), ^{
              // do something
            });
        }
    }
    

    存储部分就跳过了

    影响正常使用录音功能的因素

    • 当app处于后台时
       
      屏幕快照 2019-09-17 11.06.16.png

      设置AVAudioSession
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord /*withOptions: AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers*/ error:&error];
    
    • 录音的同时,需要使用扬声器
      设置AVAudioSession
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions: AVAudioSessionCategoryOptionDefaultToSpeaker/* | AVAudioSessionCategoryOptionMixWithOthers*/ error:&error];
    
    • 录音的同时,其他app调用了扬声器或者麦克风
      设置AVAudioSession
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions: AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers error:&error];
    
    • 录音的时候有电话打进来或者其他可能导致录音中断的情况
      监听AVAudioSessionInterruptionNotification
    - (instancetype)init {
        self = [super init];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
            [self addCallMonitor];
        }
        return self;
    }
    //audio被打断
    - (void)audioSessionInterruptionNotification:(NSNotification *)notifi {
        if (self.orderId == nil) { return ; }
        NSInteger type = [notifi.userInfo[AVAudioSessionInterruptionTypeKey] integerValue];
        switch (type) {
            case AVAudioSessionInterruptionTypeBegan: { //打断时暂停录音
                    //do something
            }break;
            case AVAudioSessionInterruptionTypeEnded: {//结束后开启录音
                NSInteger option = [notifi.userInfo[AVAudioSessionInterruptionOptionKey] integerValue];
                if (option == AVAudioSessionInterruptionOptionShouldResume) {//需要重启则重启
                    //do something
                }else {
                    //do something
                }
            }break;
        };
        NSLog(@"%@", notifi);
    }
    
    • 在打电话的时候,调用了麦克风
      由于在通话中调用麦克风会失败,所以需要监听通话结束时,恢复录音功能
    //添加电话监听
    - (void)addCallMonitor {
        if (@available(iOS 10.0, *)) {
            self.callObserver = [[CXCallObserver alloc] init];
            [self.callObserver setDelegate:self queue:dispatch_get_main_queue()];
        } else {
            self.callCenter = [[CTCallCenter alloc] init];
            [self.callCenter setCallEventHandler:^(CTCall * call) {
                if ([call.callState isEqualToString:CTCallStateDisconnected]) {//通话中断后,重新开启录音
                    //do something
                }
            }];
        }
    }
    //通话中断后,重新开启录音
    - (void)callObserver:(CXCallObserver *)callObserver callChanged:(CXCall *)call API_AVAILABLE(ios(10.0)) {
        if (call.hasEnded) {
            //do something
        }
    }
    

    总结

    上述介绍,只是罗列了一部分录音的操作,具体的实现还要根据业务不同,添加其他的逻辑,若有不明之处,可以评论沟通。不完善之处,还请慷慨指出



    作者:赛萧何
    链接:https://www.jianshu.com/p/fb7dfb033989
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    牛人读书 列表
    设计模式 简介
    java 并发编程 list
    Spring Boot 概念知识
    JS原生Date类型方法的一些冷知识
    JavaScript 操作 Cookie
    nodeJS(express4.x)+vue(vue-cli)构建前后端分离详细教程(带跨域)
    Vue学习笔记(一)
    windows下常查看端口占用方法总结
    webstorm添加*.vue文件代码提醒支持webstorm支持es6vue里支持es6写法
  • 原文地址:https://www.cnblogs.com/itlover2013/p/14414245.html
Copyright © 2020-2023  润新知