c++endiannessriff

distorted output during processing .wav file


I want to process a .wav file for example reducing amplitude; when i use following code the output becomes distorted and that's not pleasant.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    char* wav_mem;
    ifstream wav_file;
    wav_file.open("1.wav", ios::binary | ios::ate);
    int file_size = wav_file.tellg();
    wav_mem = new char[file_size];
    wav_file.seekg(0, ios::beg);
    wav_file.read(wav_mem, file_size);
    int16_t sample = 0;
    wav_file.close();
    for(int i = 44; i <= file_size; i += 2)
    {   
        sample = ((wav_mem[i + 1] << 8) | (wav_mem[i]));
        sample = (int16_t)(sample * 0.5);
        wav_mem[i] = sample;
        wav_mem[i+1] = (sample >> 8);
    }
    ofstream out_file;
    out_file.open("out.wav", ios::binary);
    out_file.write(wav_mem, file_size);
}

How can I fix the distortion?


Solution

  • I solved the problem, i messed up samples when i was trying to convert two bytes to 16 bits, here is the final code:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <string.h>
    using namespace std;
    
    int main()
    {
        ifstream wav_file;
        ofstream out_file;
        wav_file.open("input.wav",ios::binary|ios::ate);
        size_t file_size = wav_file.tellg();
        char * wav_buf = new char[file_size];
        wav_file.seekg (0,ios::beg);
        wav_file.read (wav_buf, file_size);
        wav_file.close();
        int16_t wav_smpl(0);
        char * wav_out = new char[file_size];
        memcpy(wav_out, wav_buf, 44);
        for (size_t i = 0 ; i < file_size ; i += 2) 
        {
            memcpy(&wav_smpl , wav_buf + (i + 44) , 2);
            wav_smpl *= 3;
            memcpy(wav_out + (i + 44) , &wav_smpl , 2);
        }
        out_file.open("output.wav",ios::binary);
        out_file.write(wav_out, file_size);
        out_file.close();
        return 0;
    }