c++ 正确阅读.wav文件中的样本

4ktjp1zp  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(135)

我正在尝试正确读取WAVE文件,PCM,单声道,16位(每个样本2字节)。我已经成功读取了标题。问题是阅读(写入)数据部分。
据我所知,数据块中的16位样本是little-endian,并“分裂”为两个8位的块。因此,对我来说,读取正确数据的方法应该是:
1.读取文件并将块放入两个不同的int8_t变量(或std::vector<int8_t>..)
1.以某种方式“连接”这两个变量,形成一个int16_t,并能够处理它。
问题是我不知道如何处理小字节序,而且这些样本不是无符号的,所以我不能使用〈〈操作符。
这是我做过的一个试验,没有成功:

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);
                }
}
  • 更详细地说 *,我使用了在线找到的这段代码,并从它开始创建了一个类(过程是相同的,但类配置非常长,并且有许多特性对这个问题没有用处):
#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;
}

问题出在/使用此处的波浪数据执行操作/中。我不知道如何获取样本值。

gojuced7

gojuced71#

我是一个Java程序员,不是C++,但我经常处理这个问题。
PCM数据是按帧组织的。如果是单声道、小字节序、16位,第一个字节将是值的下半部分,第二个字节将是值的上半部分,包括符号位。大字节序将反转字节。如果是立体声,完整的帧(我认为是左,然后是右,但我不确定)在移动到下一帧之前完整地呈现。
我对这里显示的所有代码感到有点惊讶。在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如何将其直接翻译成C++,但我们只是简单地将两个字节进行OR运算,第二个字节先向左移8位。纯移位选择符号位。(我不记得为什么包括& 0xff--我很久以前写过这个,它工作正常。)
奇怪为什么这么多的答案都在评论里,而不是作为答案贴出来。我以为评论是为了澄清OP的问题。

n1bvdmb6

n1bvdmb62#

类似这样的方法是可行的:

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

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; 
            }

然后通过执行以下操作在-1和1之间归一化:

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

标准化自:sms-tools
注:这适用于采样率为44100,分辨率为16位的单声道文件。

相关问题