iOS 单声道wav转mp3 lame

因为科大讯飞录音上传需要上传16000 16位 单声道文件 所以录制的wav为单声道,转码的时候出现了一些问题,通过修改一些lame的设置改正了


+(void)convertWavToMp3:(NSString*)wavFilePath withSavePath:(NSString*)savePath withBlock:(RecordConvertBlock)block {

    @try{

        intread, write;



        FILE*pcm =fopen([wavFilePathcStringUsingEncoding:1],"rb");  //source 被转换的音频文件位置

        fseek(pcm,4*1024,SEEK_CUR);                                  //skip file header

        FILE*mp3 =fopen([savePathcStringUsingEncoding:1],"wb+");  //output 输出生成的Mp3文件位置



        constintPCM_SIZE =8192;

        constintMP3_SIZE =8192;

        shortintpcm_buffer[PCM_SIZE*2];

        unsignedcharmp3_buffer[MP3_SIZE];



        lame_tlame =lame_init();

        lame_set_in_samplerate(lame, 16000);

        lame_set_VBR(lame, vbr_default);

        lame_init_params(lame);

        lame_set_num_channels(lame,1); //***修改转码的mp3文件为单声道,不设置默认是双声道

        do{

            read =fread(pcm_buffer,sizeof(shortint), PCM_SIZE, pcm); //***双声道第二个参数设置 2*sizeof(shortint)

            if(read ==0)

                write =lame_encode_flush(lame, mp3_buffer, MP3_SIZE);

            else

                write =lame_encode_buffer(lame, pcm_buffer,pcm_buffer, read, mp3_buffer, MP3_SIZE);//***单声道写入

//                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE); //***双声道写入

            fwrite(mp3_buffer, write,1, mp3);

        }while(read !=0);



        lame_mp3_tags_fid(lame, mp3);

        lame_close(lame);

        fclose(mp3);

        fclose(pcm);

    }

    @catch(NSException *exception) {

        dispatch_async(dispatch_get_main_queue(), ^{

            //更新UI操作

            block(exception.reason);

        });



    }

    @finally {

        dispatch_async(dispatch_get_main_queue(), ^{

            //更新UI操作

            NSLog(@"MP3生成成功: %@",savePath);

            block(nil);

        });



    }



}

你可能感兴趣的:(iOS 单声道wav转mp3 lame)