提问人:Jake A 提问时间:10/26/2023 最后编辑:273KJake A 更新时间:10/27/2023 访问量:18
如何将数据缓冲区从 SDL_LoadWAV 复制到 SDL_AudioCVT?
How do I copy the data buffer from SDL_LoadWAV to SDL_AudioCVT?
问:
此函数应加载 wav 并将其转换为所需的格式。 我的问题是我无法弄清楚如何正确地将数据复制到 cvt。 我从文档中收集的是音频数据是指向指针的 Uint8 指针。 我知道它必须指向某种数组,但我不知道它是如何设置的。
void load_audio()
{
string full_path = default_path;
full_path += path;
if (wav_length > 0)
{
SDL_FreeWAV(wav_buffer);
}
if (SDL_LoadWAV(full_path.c_str(), &wav_spec, &wav_buffer, &wav_length) == NULL)
{
fprintf(stderr, "Could not open wav: %s\n", SDL_GetError());
return;
}
// convert input format to U8 mono 32kHz
SDL_AudioCVT cvt;
SDL_BuildAudioCVT(&cvt, wav_spec.format, wav_spec.channels, wav_spec.freq, AUDIO_U8, 1, 32000);
SDL_assert(cvt.needed);
cvt.len = wav_length * wav_spec.channels * 2; // length of original data * 2 for 16bit
cvt.buf = (Uint8 *) SDL_malloc(cvt.len * cvt.len_mult);
// How do I copy the data from wav_buffer to cvt.buf ???
SDL_ConvertAudio(&cvt); // convert
}
wav 变量如下
SDL_AudioSpec wav_spec;
Uint32 wav_length;
Uint8 *wav_buffer;
旁注:我将加载的 wav 文件将始终为 16 位
答:
0赞
Jake A
10/27/2023
#1
答案是 memcpy() 和 cvt_len var 而不是 cvt.len
// convert input format to U8 mono 32kHz
SDL_AudioCVT cvt;
SDL_BuildAudioCVT(&cvt, wav_spec.format, wav_spec.channels, wav_spec.freq, AUDIO_U8, 1, 32000);
SDL_assert(cvt.needed); // obviously, this one is always needed.
cvt.len = wav_length * wav_spec.channels * 2; // length of original data * 2 for 16bit
cvt.buf = (Uint8 *) SDL_malloc(cvt.len * cvt.len_mult); // allocate buffer
memcpy(cvt.buf, wav_buffer, wav_length); // copy wav data to cvt buffer
SDL_ConvertAudio(&cvt); // convert
wav_length = cvt.len_cvt; // len_cvt is the actaul length after conversion
memcpy(wav_buffer, cvt.buf, cvt.len_cvt); // copy converted cvt buffer back to wav buffer
评论