1

我在 OSX 上制作基于 Libsndfile 的音频应用程序时遇到了奇怪的问题。读取和写入缓冲区中的数据以奇怪且不可预测的方式损坏。

这是一个为我重现问题的简短程序:

#include <iostream>
#include "sndfile.h"

int main(int argc, const char * argv[])
{
float* buffer = (float*)malloc(4096*sizeof(float));
SNDFILE* file;
SF_INFO infos;
infos.format = 0;
file = sf_open("ABCD.WAV",SFM_READ,&infos);
if (file==NULL)
{
    std::cout << "LIBSNDFILE ERROR: " << sf_strerror(file) << "\n";   
}

int samplesread=1;
while (samplesread!=0)
    {
        samplesread = sf_readf_float(file,buffer,4096);
        std::cout << " " << samplesread;
    }
std::cout << "";
sf_close(file);
free(buffer);
return 0;
}

该程序编译并运行良好,但使用 Valgrind 运行它会显示这种错误:

==933== Invalid write of size 8 
==933==    at 0x56EF4B: _platform_bzero$VARIANT$Merom (in    /usr/lib/system/libsystem_platform.dylib)
==933==    by 0x2FDBB: psf_memset (in /opt/local/lib/libsndfile.1.dylib)
==933==    by 0x11E0B: sf_readf_float (in /opt/local/lib/libsndfile.1.dylib)
==933==    by 0x100001323: main (in ./sndfiletest)
==933==  Address 0x873270 is 0 bytes after a block of size 16,384 alloc'd
==933==    at 0x4711: malloc (vg_replace_malloc.c:296)
==933==    by 0x100001287: main (in ./sndfiletest

提前感谢您的帮助-T

4

2 回答 2

0

您的代码的问题在于它仅适用于单声道输入文件。

你需要熟悉框架的概念,根据框架

对于帧数函数,frames 参数指定帧数。一帧只是一个样本块,每个通道一个。必须注意确保 ptr 指向的数组中有足够的空间,以获取 (frames * channels) 数量的项目(shorts、ints、float 或 doubles)。

通过使用sf_readf_float带有第三个参数的函数4096,您要求读取 4096。一帧是一个样本乘以通道数C。所以当你这样做时

sf_readf_float(file,buffer,4096);

您要求将4096*C样本存储到您声明为的缓冲区中

float* buffer = (float*)malloc(4096*sizeof(float));

你溢出了缓冲区!

要解决此问题,您有两个选择。

1.继续使用sf_readf_float并修复分配buffer

#include <stdlib.h>
#include <iostream>
#include "sndfile.h"

int main(int argc, const char * argv[])
{
  float* buffer;
  SNDFILE* file;
  SF_INFO infos;
  file = sf_open("inFile.wav",SFM_READ,&infos);

  buffer = (float*)malloc(infos.channels*4096*sizeof(float));

  if (file==NULL)
  {
    std::cout << "LIBSNDFILE ERROR: " << sf_strerror(file) << "\n";
  }

  int samplesread=1;
  while (samplesread!=0)
  {
    samplesread = sf_readf_float(file,buffer,4096);
    std::cout << " " << samplesread;
  }
  std::cout << "";

  sf_close(file);
  free(buffer);
  return 0;
}

2.保持你的缓冲区分配和使用sf_read_float

我不推荐这种方式,因为您仍然需要检查是否4096C. 在立体声输入的情况下,您可以:

#include <stdlib.h>
#include <iostream>
#include "sndfile.h"

int main(int argc, const char * argv[])
{
  float* buffer = (float*)malloc(4096*sizeof(float));
  SNDFILE* file;
  SF_INFO infos;
  file = sf_open("inFile.wav",SFM_READ,&infos);

  if (file==NULL)
  {
    std::cout << "LIBSNDFILE ERROR: " << sf_strerror(file) << "\n";
  }

  int samplesread=1;
  while (samplesread!=0)
  {
    samplesread = sf_read_float(file,buffer,4096);
    std::cout << " " << samplesread;
  }
  std::cout << "";

  sf_close(file);
  free(buffer);
  return 0;
}
于 2018-12-20T14:15:12.070 回答
0

您的 wav 文件可能是立体声的。那么你的缓冲区大小需要为 4096 * 2

于 2015-11-22T15:04:29.900 回答