简体   繁体   English

正确读取 .wav 文件中的样本

[英]Correct reading of samples from .wav file

I am trying to read correctly a WAVE file, PCM, mono, 16 bits (2 bytes per sample).我正在尝试正确读取 WAVE 文件,PCM,mono,16 位(每个样本 2 个字节)。 I have managed to read the header .我设法阅读了header The problem is reading (writing) the data part.问题是读取(写入)数据部分。

As far as I understand the 16-bit samples in the data chunk are little-endian, and "split" into two chunks of 8 bits each.据我了解,数据块中的 16 位样本是小字节序的,并且“拆分”为两个 8 位的块。 So for me a way to read the correct data should be:所以对我来说,读取正确数据的方法应该是:

  1. Read file and put chunks into two different int8_t variables (or a std::vector<int8_t> ..)读取文件并将块放入两个不同的int8_t变量(或std::vector<int8_t> ..)
  2. In some way "join" these two variables to make a int16_t and being able to process it.以某种方式“加入”这两个变量以生成int16_t并能够对其进行处理。

The problem is I have no idea on how to deal with the little-endianness and the fact that these samples aren't unsigned, so I can't use the << operator.问题是我不知道如何处理小字节序以及这些样本不是无符号的事实,所以我不能使用 << 运算符。

This is one of the test I've done, without success:这是我做过的测试之一,但没有成功:

int8_t buffer[], firstbyte,secondbyte;
int16_t result;
std::vector<int16_t> data;
while(Read bytes and put them in buffer){
for (int j=0;j<bytesReadFromTheFile;j+=2){
                    firstbyte = buffer[j];
                    secondbyte = buffer[j+1];
                    result = (firstbyte);
                    result = (result << 8)+secondbyte; //shift first byte and add second
                    data.push_back(result);
                }
}

To be more verbose , I am using this code found online and created a class starting from it (The process is the same, but the Class configuration is very long and has many features that aren't useful for this problem):更详细地说,我使用在网上找到的这段代码并从它开始创建一个 class(过程是相同的,但是 Class 配置很长并且有很多功能对这个问题没有用):

#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::string;

typedef struct  WAV_HEADER
{
    /* RIFF Chunk Descriptor */
    uint8_t         RIFF[4];        // RIFF Header Magic header
    uint32_t        ChunkSize;      // RIFF Chunk Size
    uint8_t         WAVE[4];        // WAVE Header
    /* "fmt" sub-chunk */
    uint8_t         fmt[4];         // FMT header
    uint32_t        Subchunk1Size;  // Size of the fmt chunk
    uint16_t        AudioFormat;    // Audio format 1=PCM,6=mulaw,7=alaw,     257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
    uint16_t        NumOfChan;      // Number of channels 1=Mono 2=Sterio
    uint32_t        SamplesPerSec;  // Sampling Frequency in Hz
    uint32_t        bytesPerSec;    // bytes per second
    uint16_t        blockAlign;     // 2=16-bit mono, 4=16-bit stereo
    uint16_t        bitsPerSample;  // Number of bits per sample
    /* "data" sub-chunk */
    uint8_t         Subchunk2ID[4]; // "data"  string
    uint32_t        Subchunk2Size;  // Sampled data length
} wav_hdr;

// Function prototypes
int getFileSize(FILE* inFile);

int main(int argc, char* argv[])
{
    wav_hdr wavHeader;
    int headerSize = sizeof(wav_hdr), filelength = 0;

    const char* filePath;
    string input;
    if (argc <= 1)
    {
        cout << "Input wave file name: ";
        cin >> input;
        cin.get();
        filePath = input.c_str();
    }
    else
    {
        filePath = argv[1];
        cout << "Input wave file name: " << filePath << endl;
    }

    FILE* wavFile = fopen(filePath, "r");
    if (wavFile == nullptr)
    {
        fprintf(stderr, "Unable to open wave file: %s\n", filePath);
        return 1;
    }

    //Read the header
    size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile);
    cout << "Header Read " << bytesRead << " bytes." << endl;
    if (bytesRead > 0)
    {
        //Read the data
        uint16_t bytesPerSample = wavHeader.bitsPerSample / 8;      //Number     of bytes per sample
        uint64_t numSamples = wavHeader.ChunkSize / bytesPerSample; //How many samples are in the wav file?
        static const uint16_t BUFFER_SIZE = 4096;
        int8_t* buffer = new int8_t[BUFFER_SIZE];
        while ((bytesRead = fread(buffer, sizeof buffer[0], BUFFER_SIZE / (sizeof buffer[0]), wavFile)) > 0)
        {
            * /** DO SOMETHING WITH THE WAVE DATA HERE **/ *
            cout << "Read " << bytesRead << " bytes." << endl;
        }
        delete [] buffer;
        buffer = nullptr;
        filelength = getFileSize(wavFile);

        cout << "File is                    :" << filelength << " bytes." << endl;
        cout << "RIFF header                :" << wavHeader.RIFF[0] << wavHeader.RIFF[1] << wavHeader.RIFF[2] << wavHeader.RIFF[3] << endl;
        cout << "WAVE header                :" << wavHeader.WAVE[0] << wavHeader.WAVE[1] << wavHeader.WAVE[2] << wavHeader.WAVE[3] << endl;
        cout << "FMT                        :" << wavHeader.fmt[0] << wavHeader.fmt[1] << wavHeader.fmt[2] << wavHeader.fmt[3] << endl;
        cout << "Data size                  :" << wavHeader.ChunkSize << endl;

        // Display the sampling Rate from the header
        cout << "Sampling Rate              :" << wavHeader.SamplesPerSec << endl;
        cout << "Number of bits used        :" << wavHeader.bitsPerSample << endl;
        cout << "Number of channels         :" << wavHeader.NumOfChan << endl;
        cout << "Number of bytes per second :" << wavHeader.bytesPerSec << endl;
        cout << "Data length                :" << wavHeader.Subchunk2Size << endl;
        cout << "Audio Format               :" << wavHeader.AudioFormat << endl;
        // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM

        cout << "Block align                :" << wavHeader.blockAlign << endl;
        cout << "Data string                :" << wavHeader.Subchunk2ID[0] << wavHeader.Subchunk2ID[1] << wavHeader.Subchunk2ID[2] << wavHeader.Subchunk2ID[3] << endl;
    }
    fclose(wavFile);
    return 0;
}

// find the file size
int getFileSize(FILE* inFile)
{
    int fileSize = 0;
    fseek(inFile, 0, SEEK_END);

    fileSize = ftell(inFile);

    fseek(inFile, 0, SEEK_SET);
    return fileSize;
}

The problem is in the /** DO SOMETHING WITH THE WAVE DATA HERE **/.问题出在 /** 在这里使用波形数据 **/。 I have no Idea on how to get the sample value.我不知道如何获得样本值。

I'm a Java programmer, not C++, but I've dealt with this often.我是 Java 程序员,不是 C++,但我经常处理这个问题。

The PCM data is organized by frame. PCM 数据按帧组织。 If it's mono, little-endian, 16-bit the first byte will be the lower half of the value, and the second byte will be the upper and include the sign bit.如果是 mono,little-endian,16 位,第一个字节是值的下半部分,第二个字节是上半部分,包括符号位。 Big-endian will reverse the bytes. Big-endian 将反转字节。 If it's stereo, a full frame (I think it's left then right but I'm not sure) is presented intact before moving on to the next frame.如果它是立体声的,则在继续下一帧之前,完整的帧(我认为它是从左到右,但我不确定)会完整呈现。

I'm kind of amazed at all the code being shown.我对所有显示的代码感到惊讶。 In Java, the following suffices for PCM encoded as signed values:在 Java 中,对于编码为有符号值的 PCM,以下内容就足够了:

public short[] fromBufferToPCM(short[] audioPCM, byte[] buffer)
{
    for (int i = 0, n = buffer.length; i < n; i += 2)
    {
        audioPCM[i] = (buffer[i] & 0xff) | (buffer[i + 1] << 8);
    }

    return audioBytes;
}

IDK how to translate that directly to C++, but we are simply OR-ing together the two bytes with the second one first being shifted 8 places to the left. IDK 如何将其直接转换为 C++,但我们只是将两个字节 OR-ing 在一起,第二个字节首先向左移动 8 个位置。 The pure shift picks up the sign bit.纯移位拾取符号位。 (I can't recall why the & 0xff was included--I wrote this a long while back and it works.) (我不记得为什么要包含 & 0xff ——我很久以前写过这个并且它有效。)

Curious why so many answers are in the comments and not posted as answers.很好奇为什么评论中有这么多答案而不是作为答案发布。 I thought comments were for requests to clarify the OP's question.我认为评论是为了要求澄清 OP 的问题。

something like this works:这样的事情有效:

int8_t * tempBuffer = new int8_t [numSamples];
int index_for_loop = 0; 
float INT16_FAC = pow(2,15) - 1;
double * outbuffer = new double [numSamples];

inside while loop:在 while 循环内:

for(int i = 0; i < BUFFER_SIZE; i += 2)
            { 
                firstbyte = buffer[i]; 
                secondbyte = buffer[i + 1]; 
                result = firstbyte; 
                result = (result << 8) +secondbyte; 
                tempBuffer[index_for_loop] = result; 
                index_for_loop += 1; 
            }

then normalize between -1 and 1 by doing:然后通过执行以下操作在 -1 和 1 之间归一化:

for(int i = 0; i <numSamples; i ++)
{ 
    outbuffer[i] = float(tempBuffer[i]) / INT16_FAC; 
}

got normalize from: sms-tools规范化来自: sms-tools
Note: this works for mono files with 44100 samplerate and 16 bit resolution.注意:这适用于具有 44100 采样率和 16 位分辨率的 mono 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM