Reduce the volume of a Wav audio file using C

怎甘沉沦 提交于 2019-12-01 01:50:39

To keep things simple, check all the specs of your audio file before compiling your program. A plain .wav file has the following attributes:

  • No compression (Audio format would be PCM)
  • 16 bit samples
  • Mono-channel (although your program might work with stereo)

So make sure the audio file you're parsing contains these attributes. Once you have verified that these attributes are common to your audio file, then you can begin testing. If your file does not contain these attributes, you may want to consider getting Audacity, or something similar, to make test .wav files.

Your code is a little strange. First you cast the data as a char, then to int, and then into float. That's going to give you some serious errors. All of these data types are different in size. Float also has a completely different binary format. A int of value 65 may be a float of -34564.23 (or something like that). Just use int16_t.

I also see that you've opened two files for your code - don't bother, since it makes the code bigger. Keep your code as simple as you can until it does what you want - then add the auxiliary attributes.

Also, on your fwrites you've written fwrite (&nuovoValArray[0], 1, 1, fp2) but it should be fwrite (&nuovoValArray[0], 2, 1, fp2) since the size of int16_t is 2 bytes and not 1.

When it comes to reducing the volume of the file, here's a general approach that should work:

  • Get sample samp[i] (16-bit or 2 bytes)
  • Reduce the volume: samp[i] -= (int16_t) (samp[i] * percent);
  • Increment i
  • Repeat

Here's a snippet of code that might help:

// open file
// read into char * fileBuffer

int sampleCount = ((fileSize - dataOffset) / sizeof (int16_t)); 
int16_t * samp  = (int16_t *) &fileBuffer[dataOffset];
float percent   = 0.6f;

for (int i = 0; i < sampleCount; i++){
    samp[i] -= (int16_t) (samp[i] * percent); // Should work +/- values
}

// save file

I previously had written an applications that graphs .wav files for waveform analysis. All I had to read to learn the file format was this page - it should help you as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!