背景
因?yàn)樯弦黄纛l合成中遇到了一個(gè)問題,合成工具不支持wav音頻格式轉(zhuǎn)化,而且錄音所得的wav格式 是無損的格式拄查,標(biāo)準(zhǔn)的wav采樣率為44100Hz,也是CD標(biāo)準(zhǔn)格式棚蓄;mp3屬于有損壓縮文件堕扶,不過體積小碍脏,便于保存。
lame 下載下來不能直接用
依賴的東西 :
操作步驟:
- 把下載的lame和build-lame.sh放在一個(gè)文件夾下
注意 # build-lame.sh 中 #directories SOURCE="lame"
這里lame是來源文件名
- 在創(chuàng)建的目錄下執(zhí)行 bulid 腳本
sudo ./build-lame.sh
-
下面 fat-lame 中就是我們想要的東西稍算,將.a 文件和.h文件放入項(xiàng)目即可
屏幕快照 2019-04-28 上午11.02.30.png wav 轉(zhuǎn)map3 相關(guān)代碼
#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(@"音頻文件夾創(chuàng)建失敗----%@", error);
}
}
return audioFolder;
}
//用url作為文件名
- (NSString *)audioFilePath:(NSString *)audioURL
{
NSString *fileName = [audioURL stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
return [[self audioCacheFolder] stringByAppendingPathComponent:fileName];
}
//轉(zhuǎn)化方法
- (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 被轉(zhuǎn)換的音頻文件位置
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;
}
}