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:pcmFilePathmp3FilePath:mp3FilePathsampleRate:sampleRatecallback:^(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 *)cafFilePathmp3FilePath:(NSString *)mp3FilePathcallback:(void(^)(BOOL complete))callback;+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePathmp3FilePath:(NSString *)mp3FilePathsampleRate:(int)sampleRatecallback:(void(^)(BOOL complete))callback;@endNS_ASSUME_NONNULL_END
PHAIMP3Encoder.m
#import "PHAIMP3Encoder.h"#import "lame/lame.h"#import "PHAILogFunctions.h"@implementation PHAIMP3Encoder+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePathmp3FilePath:(NSString *)mp3FilePathcallback:(void (^)(BOOL))callback {[self conventToMp3WithCafFilePath:cafFilePathmp3FilePath:mp3FilePathsampleRate:16000callback:^(BOOL complete) {callback(complete);}];}+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePathmp3FilePath:(NSString *)mp3FilePathsampleRate:(int)sampleRatecallback:(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 headerFILE *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