#include #include #include #include #include "ogg2mp3.h" #ifdef __cplusplus extern "C" { #endif #define OGG_FILE_ERROR 1 #define MP3_FILE_ERROR 2 #define OGG_DECODE_ERROR 3 #define MP3_ENCODE_ERROR 4 int convertOggToMp3(const char* oggFilePath, const char* mp3FilePath) { // 打开 OGG 文件 FILE* oggFile = fopen(oggFilePath, "rb"); if (!oggFile) { return OGG_FILE_ERROR; } // 打开 MP3 文件 FILE* mp3File = fopen(mp3FilePath, "wb"); if (!mp3File) { fclose(oggFile); return MP3_FILE_ERROR; } // 初始化 OGG 解码器 OggVorbis_File vf; if (ov_open(oggFile, &vf, NULL, 0) < 0) { fclose(oggFile); fclose(mp3File); return OGG_DECODE_ERROR; } // 获取音频信息 vorbis_info* vi = ov_info(&vf, -1); // 初始化 LAME 编码器 lame_t lame = lame_init(); lame_set_in_samplerate(lame, vi->rate); lame_set_num_channels(lame, vi->channels); lame_set_VBR(lame, vbr_default); lame_init_params(lame); // 缓冲区 const int BUFFER_SIZE = 4096; short int pcm_buffer[BUFFER_SIZE * vi->channels]; unsigned char mp3_buffer[BUFFER_SIZE]; int read, write; int current_section; // 读取 OGG 数据并编码为 MP3 while ((read = ov_read(&vf, (char*)pcm_buffer, sizeof(pcm_buffer), 0, 2, 1, ¤t_section)) > 0) { write = lame_encode_buffer_interleaved(lame, pcm_buffer, read / (2 * vi->channels), mp3_buffer, BUFFER_SIZE); fwrite(mp3_buffer, write, 1, mp3File); } // 结束编码 write = lame_encode_flush(lame, mp3_buffer, BUFFER_SIZE); fwrite(mp3_buffer, write, 1, mp3File); // 清理 lame_close(lame); ov_clear(&vf); fclose(mp3File); // fclose(oggFile); return 0; } #ifdef __cplusplus } #endif