PCM文件转换为MP3文件
简要描述
主要协助云上越秀App将PCM音频文件转码成MP3文件功能代码示例;
主要内容
PCM录制示例代码:
引入第三方库:
pod 'mp3lame-for-ios'
代码片段:
- (void)startSpeechRecognizerWithFileName:(NSString *)fileName {
[self.iFlySpeechRecognizer cancel];
self.jsons = @[].mutableCopy;
if ([PHAIUtils isNilOrEmpty:fileName]) {
self.fileName = [PHAIFileManager generateFileName];
} else {
self.fileName = fileName;
}
NSString *pcmFileName = [NSString stringWithFormat:@"%@.pcm", self.fileName];
//asr_audio_path 是录音文件名,设置value为nil或者为空取消保存,默认保存目录在Library/cache下。
[_iFlySpeechRecognizer setParameter:pcmFileName forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
//启动识别服务
[self.iFlySpeechRecognizer startListening];
}
- (void)onCompleted:(IFlySpeechError *)error {
IFlyLog(@"%s",__func__);
self.result = nil;
if (error.errorCode != 0) {
IFlyLog(@"语音识别出现问题:%@", error.errorDesc);
} else {
PHAIFileManager *fileManager = PHAIFileManager.sharedManager;
NSString *fileName = self.fileName;
NSString *pcmFilePath = [fileManager getCachesPCMURLWithName:fileName].path;
NSString *mp3FilePath = [fileManager getIATAudioFileWithName:fileName].path;
int sampleRate = [PHAIIATConfig.sharedInstance.sampleRate intValue];
__weak typeof(self) weakSelf = self;
[PHAIMP3Encoder conventToMp3WithCafFilePath:pcmFilePath
mp3FilePath:mp3FilePath
sampleRate:sampleRate
callback:^(BOOL complete) {
if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(mp3EnconderComplete:fileName:)]) {
[weakSelf.delegate mp3EnconderComplete:complete fileName:fileName];
}
AudioEncoderLog(@"转码完成");
}];
}
if (self.delegate && [self.delegate respondsToSelector:@selector(recongnizingComplete:)]) {
[self.delegate recongnizingComplete:error.errorCode == 0];
}
}
PCM转换成MP3的示例代码:
PHAIMP3Encoder.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PHAIMP3Encoder : NSObject
+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
mp3FilePath:(NSString *)mp3FilePath
callback:(void(^)(BOOL complete))callback;
+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
mp3FilePath:(NSString *)mp3FilePath
sampleRate:(int)sampleRate
callback:(void(^)(BOOL complete))callback;
@end
NS_ASSUME_NONNULL_END
PHAIMP3Encoder.m
#import "PHAIMP3Encoder.h"
#import "lame/lame.h"
#import "PHAILogFunctions.h"
@implementation PHAIMP3Encoder
+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
mp3FilePath:(NSString *)mp3FilePath
callback:(void (^)(BOOL))callback {
[self conventToMp3WithCafFilePath:cafFilePath
mp3FilePath:mp3FilePath
sampleRate:16000
callback:^(BOOL complete) {
callback(complete);
}];
}
+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
mp3FilePath:(NSString *)mp3FilePath
sampleRate:(int)sampleRate
callback:(void(^)(BOOL complete))callback {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@try {
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
if (pcm == NULL) {
if ([NSFileManager.defaultManager fileExistsAtPath:cafFilePath]) {
pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");
} else {
AudioEncoderLog(@"文件无法打开: %@ %d", cafFilePath, [NSFileManager.defaultManager fileExistsAtPath:cafFilePath]);
callback(NO);
return;
}
}
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb+"); //output 输出生成的Mp3文件位置
const int PCM_SIZE = sampleRate / 20 + 7200;
const int MP3_SIZE = PCM_SIZE;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, sampleRate);
lame_set_num_channels(lame,1);//设置1为单通道,默认为2双通道
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = (int)fread(pcm_buffer, sizeof(short int), PCM_SIZE, pcm);
if (read == 0) {
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
} else {
write = lame_encode_buffer(lame, pcm_buffer, NULL, read, mp3_buffer, MP3_SIZE);
}
fwrite(mp3_buffer, sizeof(char), write, mp3);
} while (read != 0);
lame_mp3_tags_fid(lame, mp3);
lame_close(lame);
fclose(mp3);
fclose(pcm);
} @catch (NSException *exception) {
AudioEncoderLog(@"%@",[exception description]);
if (callback) {
callback(NO);
}
}
@finally {
AudioEncoderLog(@"-----\n MP3生成成功: %@ ----- \n", mp3FilePath);
if (callback) {
callback(YES);
}
}
});
}
@end