c++ - 正在加载波形文件,但数据末尾有随机的废话,而不是预期的样本

标签 c++ audio buffer signal-processing wav

我很久以前在网上找到了一个简单的 wav header 阅读器,我已经重新开始使用它,但它似乎用单个随机重复数字替换了数据 block 末尾的大约 1200 个样本,例如-126800。样本结束时预计会出现沉默,因此数字应为零。

这是一个简单的程序:

void main() {
    WAV_HEADER* wav = loadWav(".\\audio\\test.wav");
    double sample_count = wav->SubChunk2Size * 8 / wav->BitsPerSample;

    printf("Sample count: %i\n", (int)sample_count);

    vector<int16_t> samples = vector<int16_t>();

    for (int i = 0; i < wav->SubChunk2Size; i++)
    {
        int val = ((wav->data[i] & 0xff) << 8) | (wav->data[i + 1] & 0xff);
        samples.push_back(val);
    }
    printf("done\n");
}

这是 Wav 阅读器:

typedef struct
{
    //riff
    uint32_t Chunk_ID;
    uint32_t ChunkSize;
    uint32_t Format;

    //fmt
    uint32_t SubChunk1ID;
    uint32_t SubChunk1Size;
    uint16_t AudioFormat;
    uint16_t NumberOfChanels;
    uint32_t SampleRate;
    uint32_t ByteRate;

    uint16_t BlockAlignment;
    uint16_t BitsPerSample;

    //data
    uint32_t SubChunk2ID;
    uint32_t SubChunk2Size;

    //Everything else is data. We note it's offset
    char data[];

} WAV_HEADER;
#pragma pack()

inline WAV_HEADER* loadWav(const char* filePath)
{
    long size;
    WAV_HEADER* header;
    void* buffer;

    FILE* file;

    fopen_s(&file,filePath, "r");
    assert(file);

    fseek(file, 0, SEEK_END);
    size = ftell(file);
    rewind(file);

    std::cout << "Size of file: " << size << std::endl;

    buffer = malloc(sizeof(char) * size);
    fread(buffer, 1, size, file);

    header = (WAV_HEADER*)buffer;

    //Assert that data is in correct memory location
    assert((header->data - (char*)header) == sizeof(WAV_HEADER));

    //Extra assert to make sure that the size of our header is actually 44 bytes
    assert((header->data - (char*)header) == 44);

    fclose(file);

    return header;
}

我不确定问题是什么,我已经确认没有元数据,从文件头读取的数字与实际文件之间也不存在不匹配。我假设我这边的尺寸/偏移未对齐,但我看不到它。 欢迎任何帮助。 闷闷不乐

最佳答案

WAV 只是不同音频样本格式的容器。

您对 wav 文件做出的假设在 Windows 3.11 上应该没问题:) 这些在 2021 年不成立。

无需使用自己的 Wav 文件阅读器,只需使用可用的库之一即可。我个人使用libsndfile有很好的经验几乎一直存在,非常薄,可以处理所有流行的 WAV 文件格式,以及许多其他文件格式,除非您禁用它。

这看起来像一个 Windows 程序(人们会注意到你使用的是非常 WIN32API 风格的大写结构名称 - 这有点老派);因此,您可以从 github releases 下载 libsndfile 的安装程序并直接在您的 Visual Studio 中使用它(另一个盲目猜测)。

关于c++ - 正在加载波形文件,但数据末尾有随机的废话,而不是预期的样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70627117/

相关文章:

c++ - int ** 与 int [ROWS][COLS]

c++ - openCL - 创建子缓冲区返回错误代码 13

go - 将html页面内容(缓冲区)保存到.log文件

C++ fork() 在 linux 终端上看起来很奇怪

c++ - 将 DirectX SDK 代码转换为新的 Windows 8.1 SDK 代码

Android 的媒体播放器 : Why is an audio loop not staying synced with metronome playing at the same BPM?

qt - 对于移动应用程序中的大量音频文件,最佳策略是什么?

javascript - 在PHP循环中播放声音onclick

C++ 如何在 ofstream 中实际使用 pubsetbuf?

c++ - 如何找出哪些函数没有内联