Search code examples
c++cwavbinaryfilesfstream

Reading and writing binary files in C++


I am entirely new to C++ with just a couple of hours self-teaching, that started yesterday. SO:

I have a uncompressed simple beep.wav file, just about 3 seconds long with a single beeping sound in it.

What I am ultimately trying to achieve is, just to read the file, and at the same time write the binary data, all including: the header, ftm and data or all that is hex readable data and dump it into a simple beep.txt file.

is this possible, in C++? If so, how should I begin reading and dumping the binary file?

I can read the file ~more or less, using the <fstream> class

#include <iostream>
#include <fstream>

   int main()
   {
       ifstream myfile ("beep.wav", ios::in|ios::binary|ios::ate);
       if (myfile.is_open())
       {
        //reading goes here
        }
       return 0;
    }

Solution

  • As mentioned by yzt, you need to know by advance what's in your .wav and in which order. As far as I know, you will have tags, headers and values (samples) as well as compression informations. So, to give a start :

    If you know, by example, that the very first thing to do is to read the compression rate, you'll start your reading process by extracting may be a double :

    ifstream myfile("beep.wav", ios::in|ios::binary);
    
    double compression_rate;
    myfile.read((char*)&compression_rate, sizeof(compression_rate));
    
    // As well as probably the sample rate...
    double sample_rate;
    myfile.read((char*)&sample_rate, sizeof(sample_rate));
    

    Then, may be, the number of samples :

    int nb_samples;
    myfile.read((char*)&nb_samples, sizeof(nb_samples));
    

    Then, the values for those samples... (here stored as a vector of double)

    vector<double> vect;
    vect.resize(nb_samples);
    myfile.read((char*)&vect[0], nb_samples * sizeof(double));
    

    Etc...

    But again, what the .wav you opened is made of ?

    Once you completely master the content, you can go the other way and start writing your own .wav from scratch...


    Getting started - and here.

    Bytes - "Autopsy" of a PCM Wav file.