在 libsndfile 中一次写入一个通道

Writing to one channel at a time in libsndfile

本文关键字:一个 通道 一次 libsndfile      更新时间:2023-10-16

我正在尝试生成一个正弦波,该正弦波以 1 秒的间隔在立体声 wav 文件的左右声道之间切换,但我找不到任何方法在保持另一个声道静音的同时写入一个声道。这是我必须写入一个通道的代码:

for (int f = 0; f < numFrames; f++) {
double time = f * duration / numFrames;
buffer[f] = sin(2.0 * pi * time * freq);

以下是我发现的一些代码,可用于将两个单声道 wav 文件混合在一起:

short* mixdown = new short[2 * sizeof(short) * 800000];
for (int t = 0; t < 800000 * 2; ++t) {
mixdown[t] = (buffer1[t] + buffer2[t]) / 2;
}
FILE* process2 = _popen("ffmpeg -y -f s16le -acodec pcm_s16le -ar 44100 -ac 2 -i - -f vob -ac 2 D:\audioMixdown.wav", "wb");
fwrite(mixdown, 2 * sizeof(short) * 800000, 1, process2);

我已经浏览了 libsndfile API http://www.mega-nerd.com/libsndfile/api.html 但找不到任何关于写入通道的内容。如果有人有任何想法,最好的方法是什么,我很想听听你的意见。

您只需将零个样本写入"静音"通道即可实现此目的,例如(使右侧通道静音(:

for (int f = 0; f < numFrames; f++)
{
double time = f * duration / numFrames;
buffer[f * 2] = sin(2.0 * pi * time * freq);
buffer[f * 2 + 1] = 0;
}

这假设libsndfile期望交错格式的通道数据(我相信这是真的,但不确定(。

假设通道在缓冲区中交错,请执行以下操作:

for (int f = 0; f < numFrames; f+=2) {
...
int odd = seconds % 2;
buffer[f+odd] = sin(2.0 * pi * time * freq);
buffer[f+1-odd] = 0.0;