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

change frequency at runtime

May 24, 2012 at 11:41 AM

hello,

I want to change the frequency of sin curse with a trackbar and play the sound with the frequnce in real time.

here is my code for the change of the trackbar:

private void tbFrequenz_Scroll(object sender, EventArgs e)
{
int freq = tbFrequenz.Value;
lblFrequenz.Text = "Frequenz : " + freq.ToString();
WaveTone tone = new WaveTone(freq, 0.25f);
stream = new BlockAlignReductionStream(tone);

output = new DirectSoundOut();
output.Stop();
output.Init(stream);
output.Play();
}

thanks for the help

Coordinator
May 25, 2012 at 9:11 AM

I don't know what your WaveTone class does, but I would suggest you switch to using a WaveTable approach to sine wave generation. Create a sine wave in an array, and then adjust the delta for indexing that table in real-time. This also allows you to introduce portamento to glide between frequencies smoothly.

May 25, 2012 at 5:18 PM

Here is the code of the wavetone class:

  public class WaveTone : WaveStream
{
private double frequency;
private double amplitude;
private double time;

public WaveTone(double f, double a)
{
this.time = 0;
this.frequency = f;
this.amplitude = a;
}

public override long Position
{
get;
set;
}

public override long Length
{
get { return long.MaxValue; }
}

public override WaveFormat WaveFormat
{
get { return new WaveFormat(44100, 16, 1); }
}

public override int Read(byte[] buffer, int offset, int count)
{
int samples = count / 2;
for (int i = 0; i < samples; i++)
{
double sine = amplitude * Math.Sin(Math.PI * 2 * frequency * time);
time += 1.0 / 44100;
short truncated = (short)Math.Round(sine * (Math.Pow(2, 15) - 1));
buffer[i * 2] = (byte)(truncated & 0x00ff);
buffer[i * 2 + 1] = (byte)((truncated & 0xff00) >> 8);
}

return count;
}
}

May 26, 2012 at 4:13 PM

just create a property that changes the field frequency. Thats all.