赞
踩
为了iPhone 与 Android 实现音频互通. Mp3格式的音频文件再好不过了.这里主要用到lame(Mp3音频编码器).
首先使用 AVAudioRecorder 进行音频录制之前,进行如下参数设置:(一定要设置成pcm线性编码格式)
- // 定义音频的编码参数, 决定录制音频文件的格式, 音质, 容量大小等, 建议采用AAC的编码方式
- let recordSettings = [AVSampleRateKey: NSNumber(value: Float(44100.0)), // 声音采样率
- AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM), // 编码格式
- AVNumberOfChannelsKey: NSNumber(value: 2), //采集音轨
- AVEncoderAudioQualityKey: NSNumber(value: Int32(AVAudioQuality.medium.rawValue)), // 音频质量
- AVLinearPCMBitDepthKey: NSNumber(value: 16),
- AVLinearPCMIsFloatKey: NSNumber(value: false),
- AVLinearPCMIsBigEndianKey: NSNumber(value: false)]
lame 静态库主要有两个核心文件:
1:lame库加入工程中
2:核心转换代码(这里的代码直接引用oc的)(该处直接引用大神代码)
- - (void)audio_PCMtoMP3
- {
- NSString *mp3FileName = [self.audioFileSavePath lastPathComponent];
- mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
- NSString *mp3FilePath = [self.audioTemporarySavePath stringByAppendingPathComponent:mp3FileName];
-
- @try {
- int read, write;
-
- FILE *pcm = fopen([self.audioFileSavePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
- fseek(pcm, 4*1024, SEEK_CUR); //skip file header
- FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
-
- 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, 11025.0);
- lame_set_VBR(lame, vbr_default);
- lame_init_params(lame);
-
- do {
- read = 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);
-
- } while (read != 0);
-
- lame_close(lame);
- fclose(mp3);
- fclose(pcm);
- }
- @catch (NSException *exception) {
- NSLog(@"%@",[exception description]);
- }
- @finally {
- self.audioFileSavePath = mp3FilePath;
- NSLog(@"MP3生成成功: %@",self.audioFileSavePath);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
lame静态库(支持64架构) https://pan.baidu.com/s/1dFHtTk9 提取码: smiw
demo地址:https://github.com/songhaisheng/SGRecorder
简书博客地址
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。