gpt4 book ai didi

c++ - 音频转换 (LAME) C++ WAV -> MP3

转载 作者:搜寻专家 更新时间:2023-10-31 01:51:12 29 4
gpt4 key购买 nike

下午好。抱歉,我的英语说得不太好。

几天来,我一直在尝试将 WAV 转换为 MP3。为此,我使用 LAME。我可以使用以下命令通过命令提示符转换文件:

lame.exe-B128 - resample 8-mj \ "C: \ \ test.wav \" \ "C: \ \ test.mp3 \"

但我不想通过命令行(为了跨操作系统的可移植性),但我不能在 C++ 中执行(通过 LAME 库)。

这是我的代码:

int main()
{
//...
//...
// extraction of PCM audio data file .wav in file.pcm
short read, write;

FILE *pcm = fopen("file.pcm", "rb");
FILE *mp3 = fopen("file.mp3", "wb");

const int PCM_SIZE = 18424;
const int MP3_SIZE = 13424;

short int pcm_buffer[PCM_SIZE];
unsigned char mp3_buffer[MP3_SIZE];

lame_t lame = lame_init();

if ( lame == NULL ) {
cout<<"Unable to initialize MP3"<<endl;
return -1;
}

lame_set_num_channels(lame, 1);
lame_set_in_samplerate(lame, 8000);
lame_set_out_samplerate(lame, 8000);
lame_set_brate(lame, 128);
lame_set_mode(lame, MONO);
lame_set_quality(lame, 2);
lame_set_bWriteVbrTag(lame, 0);
if (( lame_init_params(lame)) < 0) {
cout << "Unable to initialize MP3 parameters"<<endl;
return -1;
}

do {
read = fread(pcm_buffer,sizeof(short), 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);

return 0;
}

我得到一个质量很差的 MP3 文件(持续时间比原始文件短)。

有什么解决问题的办法吗?

这是我的信息。

Wav:
- Frequency= 8000
- BlocSize= 16
- Canal Nomber= 1 (mono)
- BytePerSec= 16000
- BytePerBloc= 2
- BitsPerSample= 16
- Bitrate= 128
- .wav size: 13466 (ie size of PCM: 13422)

谢谢。

最佳答案

 @try
{
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source
fseek(pcm, 4*1024, SEEK_CUR); //skip file header

mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output
const int PCM_SIZE = 8192*3;
const int MP3_SIZE = 8192*3;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];

lame_t lame = lame_init();
lame_set_in_samplerate(lame, 11025*2);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);

int nTotalRead=0;

do {
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);

nTotalRead+=read*4;

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);
// write = lame_encode_buffer(lame, pcm_buffer,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]);
}

关于c++ - 音频转换 (LAME) C++ WAV -> MP3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056188/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com