This project has moved. For the latest updates, please go here.

How to output a sound wave to only left or right channel?

Jan 9, 2011 at 12:08 PM

Hello. I just tried to use following method to generate sound wave in different frequencies.

class SineWaveOscillator : WaveProvider16
    {
        double phaseAngle;

        public SineWaveOscillator(int sampleRate) :
            base(sampleRate, 1)
        {
        }

        public double Frequency { set; get; }
        public short Amplitude { set; get; }

        public override int Read(short[] buffer, int offset,
          int sampleCount)
        {

            for (int index = 0; index < sampleCount; index++)
            {
                buffer[offset + index] =
                  (short)(Amplitude * Math.Sin(phaseAngle));
                phaseAngle +=
                  2 * Math.PI * Frequency / WaveFormat.SampleRate;

                if (phaseAngle > 2 * Math.PI)
                    phaseAngle -= 2 * Math.PI;
            }
            return sampleCount;
        }
    }

public void soundPlay()
{
WaveOut w = new WaveOut();
SineWaveOscillator s = new SineWaveOscillator(44100);
s.frequency=1000;
s.amplitude=8192;
w.Init(s);
w.Play();
}


It seems OK but I still have a problem. How can I output this wave to only one channel, left channel or right channel?

Thank you a lot.

Coordinator
Jan 10, 2011 at 1:44 PM

make it a stereo WaveProvider and every other sample should be zero (samples go left channel followed by right channel)

Mark

Jan 10, 2011 at 4:15 PM

You mean sample in buffer[] is like [left, right, left, right, left...]?

I correct the program like following, but the sound turns to be not constant, like dudududududu...Why?

 

for (int index = 0; index < sampleCount; index+=2)
            {
                buffer[offset + index] =
                  (short)(Amplitude * Math.Sin(phaseAngle));

                 buffer[offset + index+1] =
                  (short)(Amplitude * Math.Sin(phaseAngle));
                phaseAngle +=
                  2 * Math.PI * Frequency / WaveFormat.SampleRate;

                if (phaseAngle > 2 * Math.PI)
                    phaseAngle -= 2 * Math.PI;
            }

Coordinator
Jan 10, 2011 at 4:16 PM

you also need to make the output stereo:

        public SineWaveOscillator(int sampleRate) :
            base(sampleRate, 2)
        {
        }

Jan 10, 2011 at 4:24 PM
Edited Jan 10, 2011 at 4:40 PM

it has already been changed to 2 but it sounds like dududududu...

Coordinator
Jan 10, 2011 at 4:31 PM

strange. I would output a bit of it to a WAV file and examine it with a WAV reader to see what is going on.

Mark

Jan 10, 2011 at 4:33 PM

It's OK. My fault. Some old method was not deleted.

solved. Thank you a lot.