找一个C++实现将PCM文件转换成MP3文件的代码,要求转换前后播放效果没有差异,能正常的播放,要能成功转换,使用第三方库或者自己编写代码实现都行,谢谢!
6条回答 默认 最新
- DarrenPig 2023-08-16 20:15关注
#include <stdio.h> #include <lame/lame.h> bool convertPcmToMp3(const char* pcmFilePath, const char* mp3FilePath, int sampleRate, int channels, int bitRate) { FILE *pcmFile = fopen(pcmFilePath, "rb"); if (!pcmFile) { return false; } FILE *mp3File = fopen(mp3FilePath, "wb"); if (!mp3File) { fclose(pcmFile); return false; } const int PCM_SIZE = 8192; const int MP3_SIZE = 8192; short pcmBuffer[PCM_SIZE * channels]; unsigned char mp3Buffer[MP3_SIZE]; lame_t lame = lame_init(); lame_set_num_channels(lame, channels); lame_set_in_samplerate(lame, sampleRate); lame_set_out_samplerate(lame, sampleRate); lame_set_brate(lame, bitRate); lame_set_mode(lame, channels == 1 ? MONO : STEREO); lame_set_quality(lame, 2); lame_init_params(lame); bool success = true; int readSize = 0; int writeSize = 0; do { readSize = fread(pcmBuffer, sizeof(short) * channels, PCM_SIZE, pcmFile); if (readSize != 0) { if (channels == 1) { writeSize = lame_encode_buffer(lame, pcmBuffer, NULL, readSize, mp3Buffer, MP3_SIZE); } else { writeSize = lame_encode_buffer_interleaved(lame, pcmBuffer, readSize, mp3Buffer, MP3_SIZE); } fwrite(mp3Buffer, sizeof(unsigned char), writeSize, mp3File); } else { // Flush the last bit of data. writeSize = lame_encode_flush(lame, mp3Buffer, MP3_SIZE); fwrite(mp3Buffer, sizeof(unsigned char), writeSize, mp3File); } } while (readSize != 0); lame_close(lame); fclose(pcmFile); fclose(mp3File); return success; } int main() { const char* pcmFilePath = "input.pcm"; const char* mp3FilePath = "output.mp3"; int sampleRate = 44100; // 采样率(Hz) int channels = 2; // 声道数(1:单声道,2:立体声) int bitRate = 128; // 比特率(kbps) bool success = convertPcmToMp3(pcmFilePath, mp3FilePath, sampleRate, channels, bitRate); if (success) { printf("PCM to MP3 conversion completed.\n"); } else { printf("Failed to convert PCM to MP3.\n"); } return 0; }
解决 无用评论 打赏 举报