背景
因为上一篇音频合成中遇到了一个问题,合成工具不支持wav音频格式转化,而且录音所得的wav格式 是无损的格式,标准的wav采样率为44100Hz,也是CD标准格式;mp3属于有损压缩文件,不过体积小,便于保存。
lame 下载下来不能直接用
依赖的东西 :
操作步骤:
- 把下载的lame和build-lame.sh放在一个文件夹下
注意 # build-lame.sh 中 #directories SOURCE="lame"
这里lame是来源文件名
- 在创建的目录下执行 bulid 脚本
sudo ./build-lame.sh
-
下面 fat-lame 中就是我们想要的东西,将.a 文件和.h文件放入项目即可
wav 转map3 相关代码
#define AUDIOCACHE @"音频存放目录"
文件管理
#define FILEMANAGER [NSFileManager defaultManager]
- (NSString *)documentPath
{
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
return documentPath;
}
- (NSString *)audioCacheFolder
{
NSString *audioFolder = [[self documentPath] stringByAppendingPathComponent:AUDIOCACHE];
if (![FILEMANAGER fileExistsAtPath:audioFolder]) {
NSError *error = nil;
[FILEMANAGER createDirectoryAtPath:audioFolder withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"音频文件夹创建失败----%@", error);
}
}
return audioFolder;
}
//用url作为文件名
- (NSString *)audioFilePath:(NSString *)audioURL
{
NSString *fileName = [audioURL stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
return [[self audioCacheFolder] stringByAppendingPathComponent:fileName];
}
//转化方法
- (NSString *)audioPCMtoMP3:(NSString *)wavPath {
NSString *cafFilePath = wavPath;
NSString *mp3FilePath = [self audioFilePath];
if([FILEMANAGER removeItemAtPath:mp3FilePath error:nil]){ NSLog(@"删除原MP3文件");
}
@try
{
int read, write;
FILE *pcm = fopen([cafFilePath 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, 22050.0);
lame_set_in_samplerate(lame, 4000.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]);
return @"";
} @finally {
return mp3FilePath;
}
}