.wav C++数据输出不正确

.wav C++ data not outputting correctly

本文关键字:不正确 输出 数据 C++ wav      更新时间:2023-10-16

所以我知道我以前问过这个问题,但是,在我继续我的项目之前,我仍然被卡住了。基本上,我正在尝试读取.wav文件,我已经读取了所有必需的头信息,然后将所有数据存储在char数组中。这一切都很好,但是,我将数据重新转换为整数,并尝试输出数据。

我已经在MatLab中测试了数据,然而,我得到了非常不同的结果:

Matlab-0.0078

C++:1031127695

现在这些都是非常错误的结果,这里有人好心地说,这是因为我将其输出为整数,然而,我几乎尝试了每一种数据类型,但仍然得到了错误的结果。有人认为这可能与无尽有关(http://en.wikipedia.org/wiki/Endianness)。。这看起来合乎逻辑吗?

这是代码:

bool Wav::readHeader(ifstream &file)
{
file.read(this->chunkId,                                 4);
file.read(reinterpret_cast<char*>(&this->chunkSize),     4);
file.read(this->format,                                  4);
file.read(this->formatId,                                4);
file.read(reinterpret_cast<char*>(&this->formatSize),    4);
file.read(reinterpret_cast<char*>(&this->format2),       2);
file.read(reinterpret_cast<char*>(&this->numChannels),   2);
file.read(reinterpret_cast<char*>(&this->sampleRate),    4);
file.read(reinterpret_cast<char*>(&this->byteRate),      4);
file.read(reinterpret_cast<char*>(&this->align),         2);
file.read(reinterpret_cast<char*>(&this->bitsPerSample), 4);
char testing[4] = {0};
int testingSize = 0;
while(file.read(testing, 4) && (testing[0] != 'd' ||
                                testing[1] != 'a' ||
                                testing[2] != 't' ||
                                testing[3] != 'a'))
{
file.read(reinterpret_cast<char*>(&testingSize), 4);
file.seekg(testingSize, std::ios_base::cur);
  }
      this->dataId[0] = testing[0];
      this->dataId[1] = testing[1];
      this->dataId[2] = testing[2];
      this->dataId[3] = testing[3];
     file.read(reinterpret_cast<char*>(&this->dataSize),     4);
     this->data = new char[this->dataSize];
     file.read(data,                     this->dataSize);
     unsigned int *te;
     te = reinterpret_cast<int*>(&this->data);
     cout << te[3];
     return true;
     }

如有任何帮助,我们将不胜感激。我希望我已经提供了足够的细节。

谢谢。

我认为您的代码有几个问题。其中一个是演员阵容,例如这个:

 unsigned int *te;                           
 te = reinterpret_cast<int*>(&this->data);     // (2)
 cout << te[3];                                

te是指向unsigned int的指针,而您尝试强制转换为指向int的指针。我预计第(2)行会出现编译错误。。。

你所说的te[3]是什么意思?我希望在这里输出*(te+3)内存位置的一些垃圾。