WAV 写入功能写入立体声后无法同步

WAV writing function can't sync after writing to stereo

我正在尝试使用以下函数从交错输入缓冲区创建 2 声道立体声 .wav 文件。该函数在稍微修改为写入 1 通道单声道文件时工作正常,但在其当前状态下它 returns 抛出异常错误:

void audiowrite(double* inputBuffer, int bufferLength, int fs, std::string outputFileLocation){
    SF_INFO info;
    info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
    info.channels = 2;
    info.samplerate = fs;

    SNDFILE* sndFile = sf_open(outputFileLocation.c_str(), SFM_WRITE, &info);

    sf_writef_double(sndFile, inputBuffer, bufferLength);

    sf_write_sync(sndFile); //Exception thrown - access violation reading location
    sf_close(sndFile);
}

我几乎可以肯定问题出在这个函数的某个地方,因为将输入缓冲区更改为不同的值不会改变任何东西。如果有人能够立即看到此功能有什么问题,我将不胜感激。

我最好的猜测和这个函数的典型错误是 inputBuffer 太短了。

当你使用sf_writef_double时,第三个参数的单位是帧(即样本*nb_channels)。

来自 documentation:

For the frames-count functions, the array is expected to be large enough to hold a number of items equal to the product of frames and the number of channels.

您可以通过以下任一方法修复它:

double inputBuffer[bufferLength];
...
void audiowrite(double* inputBuffer, int bufferLength, int fs, std::string outputFileLocation){
...
  sf_writef_double(sndFile, inputBuffer, bufferLength/2); // Unit is frame
...
}

double inputBuffer[bufferLength];
...
void audiowrite(double* inputBuffer, int bufferLength, int fs, std::string outputFileLocation){
...
  sf_write_double(sndFile, inputBuffer, bufferLength); // Remove the 'f' unit is sample not frame
...
}

这也可以解释为什么 mono-channel 没有出现错误,因为在这种情况下,frame = sample.