iOS PCM文件转MP3格式

来源:互联网 发布:cf显示网络出现异常 编辑:程序博客网 时间:2024/06/03 16:11
介绍下我再项目中用到的一个技术点。开发中遇到这样一个需求就是将文本转为语音,并已倒计时的方式显示读秒。大家都知道iOS7.0之后,苹果就提供
 AVSpeechSynthesizer这个类公开发者使用完成文本转语音,也很好用。但是他只能满足我第一个需求,并不能完成读秒进行显示。这样我在开发中就用到了一个第三方库,既可以将文本转语音也能读秒进行显示。只不过生成的音频文件是.pcm格式的,这样就需要我们转码进行播放,因为iOS无法直接播放.pcm文件。下面就详细说一下PCM转MP3的核心代码
在之前需要导入lame库,这个可以在网上下载导入。
code:

- (void)audio_PCMtoMP3

{

//    NSString *mp3FilePath = [[[NSBundle mainBundle] stringByAppendingPathComponent:self.recorderName] stringByAppendingPathExtension:@"mp3"];

    NSString *mp3FilePath = [NSString stringWithFormat:@"%@b.mp3",NSTemporaryDirectory()];

    NSString *_recordFilePath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"pcm"];

    @try {

        int read, write;

        

        FILE *pcm = fopen([_recordFilePath 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;//8192

        const int MP3_SIZE = 8192;//8192

        short int pcm_buffer[PCM_SIZE*2];

        unsigned char mp3_buffer[MP3_SIZE];

        

        lame_t lame = lame_init();

        lame_set_in_samplerate(lame, 7500.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 {

        //do some

    }

    

}

代码中lame库进行转码,最后完成PCM文件转MP3格式

0 0
原创粉丝点击