[英]Audio speed changes on converting WAV to MP3
I create a WAV
( PCM
) to MP3
converter.我创建了一个WAV
( PCM
) 到MP3
转换器。 But the output is too fast.但是输出太快了。
This is the code, that converts the encoding.这是转换编码的代码。
FILE *pcm = fopen(in_path, "rb");
FILE *mp3 = fopen(out_path, "wb");
int read, write;
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, sampleRate);
lame_set_brate(lame, byteRate);
lame_set_num_channels(lame, channels);
lame_set_mode(lame, MONO);
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);
The parameters sampleRate
, byteRate
and channels
are read from the WAV header.参数sampleRate
、 byteRate
和channels
从 WAV 标头中读取。
I believe something is missing in the code....我相信代码中缺少某些东西....
You are setting it up to encode a mono stream ( lame_set_mode(lame, MONO);
) but providing the data as if it were interleaved stereo.您将其设置为对单声道流进行编码( lame_set_mode(lame, MONO);
),但提供数据就好像它是交错立体声一样。
If it's a mono stream, then remove the 2*
from fread
, to read enough samples for a single channel;如果它是单声道流,则从fread
删除2*
,以便为单个通道读取足够的样本; and call lame_encode_buffer
rather than lame_encode_buffer_interleaved
, with the right-hand channel pointer set to either NULL
or pcm_buffer
, to encode just one channel.并调用lame_encode_buffer
而不是lame_encode_buffer_interleaved
,右侧通道指针设置为NULL
或pcm_buffer
,以仅编码一个通道。
If it's a stereo stream, then don't set the mode to mono.如果是立体声流,则不要将模式设置为单声道。 You probably shouldn't do this anyway;无论如何,您可能不应该这样做; I think it detects the mode based on the number of channels.我认为它根据通道数检测模式。
Also, as I mentioned when I wrote that code , you should check for and handle errors if you're using it in a real application.此外,正如我在编写该代码时提到的,如果您在实际应用程序中使用它,您应该检查并处理错误。 It's a very basic example.这是一个非常基本的例子。
If you are dealing with Mono sound, remember to set the channel to 1如果您正在处理 Mono 声音,请记住将通道设置为 1
if (channel == 1) {
lame_set_num_channels(lame, 1);
lame_set_mode(lame, MONO);
}
Also update the encoding function同时更新编码功能
if (channel == 1) {
write = lame_encode_buffer(lame, pcm_buffer, NULL, read, mp3_buffer, MP3_SIZE);
}else{
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.