Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono WAV playing on both channels

Tags:

c

audio

wav

I created a random mono WAV, but when I play it, I can hear the audio through both channels (left & right). Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

struct wav{
    char ChunkID[4];
    unsigned int ChunkSize;
    char Format[4];
    char Subchunk1ID[4];
    unsigned int Subchunk1Size;
    unsigned short int AudioFormat;
    unsigned short int NumChannels;
    unsigned int SampleRate;
    unsigned int ByteRate;
    unsigned short int BlockAlign;
    unsigned short int BitsPerSample;
    char SubChunk2ID[4];
    unsigned int Subchunk2Size;
};

int main(){

    struct wav wavHdr;
    FILE *fp;

    fp = fopen("MonoSound.wav", "wb");

    strcpy(wavHdr.ChunkID, "RIFF");
    strcpy(wavHdr.Format, "WAVE");
    strcpy(wavHdr.Subchunk1ID, "fmt ");
    wavHdr.Subchunk1Size = 16;
    wavHdr.AudioFormat = 1;
    wavHdr.NumChannels = 1;
    wavHdr.SampleRate = 220505;
    wavHdr.ByteRate = 441010;   //(SampleRate*NumChannels*BitsPerSample/8)
    wavHdr.BlockAlign = 2;     //(NumChannels*BitsPerSample/8)
    wavHdr.BitsPerSample = 16;
    strcpy(wavHdr.SubChunk2ID, "data");
    /* multiplied by 5 because there's 5 seconds of audio */
    wavHdr.Subchunk2Size = (5 * wavHdr.ByteRate);
    wavHdr.ChunkSize = (wavHdr.Subchunk2Size + 36);

    fwrite(&wavHdr, 44, 1, fp);

    int i, randVal;
    unsigned int audio;
    float freq = 50.0;
    int amp = 32600;
    float w;

    srand(time(NULL));

    for(i = 0; i < (5 * wavHdr.SampleRate); i++){
        randVal = (rand() % 1) + 1;
        amp += randVal;
        w = 2.0 * 3.141592 * freq;
        audio = amp * sin(w * i / 220505.0);
        fwrite(&audio, 2, 1, fp);
    }

    return 0;
}

What have I done wrong here? The audio should only come out through one of the speakers. Thanks in advance for the help.

like image 588
01001000 01101001 Avatar asked Apr 21 '15 05:04

01001000 01101001


2 Answers

"The audio should only come out through one of the speakers"

Not really. When you have mono file i.e. you had one microphone when you were recording the audio, you will get same data on both output channels. If you want to hear audio only from one channel make 2 channel wav, with one channel all zeros

like image 162
Dabo Avatar answered Sep 18 '22 05:09

Dabo


The audio should only come out through one of the speakers

Why do you you think so? Probably the audio driver tries to be smart and plays mono signals through both speakers (like all other consumer audio hardware does).

If you want to be sure that a signal is played on the left channel only, you have to create a stereo signal with the right channel set to silence (all zeros).

like image 24
DrKoch Avatar answered Sep 18 '22 05:09

DrKoch