I'm trying to delete the right channel from a .wav file but to no avail. Some information about the original header:
NumChannels : 2, BlockAlign : 4, BitsPerSample : 16
From this I get that the sample size is 4 bytes(2Left + 2Right) so I'm creating a new file, writing the original header to it and then writing 4 bytes at a time to the new file from the original file with an AND mask 0xffff0000 to zero the right channel. Although it does seem like the volume from the right channel is decreased by 90%, I'm looking for some improvements. Parts of Code below:
int convertToMono(char *original) {
Header *header = malloc(sizeof(Header));
getHeader(header, original);
FILE *fp = fopen(original, "rb");
fseek(fp, HEADER_SIZE, 0);// Advance HEADER_SIZE bytes to data section
// Create new file name
char *name = malloc((5 + strlen(original)) * sizeof(char));
strcpy(name, "new-");
strcat(name, original);
// Open new file and write the header to it
FILE *new = fopen(name, "wb");
fwrite(header, HEADER_SIZE, 1, new);
u_int sample = 0;// unsigned int, size in bytes == 4
for (int i = 0; i < header->chunkSize - HEADER_SIZE + 8; i += sizeof(u_int)) {
fread(&sample, sizeof(u_int), 1, fp);
sample = (sample & 0xffff0000);
fwrite(&sample, sizeof(u_int), 1, new);
}
fclose(fp);
fclose(new);
free(name);
return 0;
}
Edit: Added a picture from audio as displayed by Audacity.
To convert to mono, first you have to change the header information that are associated with the field numChannels:
header->numChannels = 1;
header->subchunk2Size /= 2;
header->chunkSize = header->subchunk2Size + 36;
header->byteRate /= 2;
header->blockAlign /= 2;
Then you open the new file and write the modified header to it:
FILE *fp2 = fopen("new.wav", "wb");
fwrite(header, HEADER_SIZE, 1, fp2);
Create a buffer that can hold sample halves:
size_t channel_size = (size_t) (header->bitsPerSample / 8);
char sample[channel_size];
Read and write the left channel and ignore the right channel for all the samples.
for (int i = 0; i < header->subchunk2Size; i += channel_size) {
fread(sample, channel_size, 1, fp1);
fwrite(sample, channel_size, 1, fp2);
fread(sample, channel_size, 1, fp1);
}
This will create a file that is half of the original in size and only the left channel will be heard. Note: This does not mean that the sound will only come from the left earphone.