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