c++ - 将波形文件读入带符号的 float 组

标签 c++ casting binary wav

使用以下代码,我可以将波形文件读入 float 组。然而,波的负端最终成为正端,因此:-MAX -> 0 和“-0”-> MAX。我不太清楚如何正确地做到这一点。我确实意识到 wave 的 header 部分可能超过 44 个字节长,但对于这个应用程序,它不会发生。我希望你们中的一个好人能帮助我 :-)

string filename;
getline(cin, filename);

ifstream wavFile(filename, ios::binary | ios::ate);

if (!wavFile) 
    cout << "error reading file\n";

int size = wavFile.tellg();
wavArray = new unsigned char[size];
wavFile.seekg(0, ios::beg);
wavFile.read((char *)wavArray, size);
wavFile.close();


int j = 1;
for (int i = 0; i < 262; i++)
{
    unsigned int tmp = (wavArray[i + 44] | (wavArray[i + 45] << 8));
    printf("%d : %f \n", k, (tmp / 32768.0));
    j++;
    i++;
}

最佳答案

问题是您对 tmp 使用了 unsigned多变的。所以 tmp 永远不会有负值,即使样本为负。试试这个

int16_t tmp = (wavArray[i + 44] | (wavArray[i + 45] << 8));

你应该#include <cstdint>得到int16_t类型。

关于c++ - 将波形文件读入带符号的 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54429892/

相关文章:

c++ - Clang:将特定警告标记为非错误

类型转换负数

c++ - 将文件编码为 1/0 二进制文件并在 C++ 中从中重建原始文件

c++ - 将 'this' 指针作为 LPARAM 传递

c++ - 将 char[] 转换为 unsigned int 得到 : dereferencing type-punned pointer will break strict-aliasing rules

c - 我不断收到此错误 : invalid operands to binary ^ (have 'double' and 'double' )

ASCII 和二进制之间的转换器和压缩器

具有在初始化时定义的不同行为的 C++ 成员函数

c++ - windows上qt连接oracle数据库

c++ - vector<double> 被转换为 vector<double, allocator<double>>