Generating Wave Forms

A small post on using JaybirdLabs.Chirp

Posted by jthomas on May 26, 2022

This is a small post that goes with the JaybirdLabs.Chirp NuGet Package as well as available on GitHub.

It turns out that it's not too hard to make audio in .Net..

Generating and playing wave forms turns out to be easy in general. If you were to imagine how it without prior reading, you would probably guess correctly. What does it involve?

  1. Write a header section signifying that this is a WAVE file.
  2. Write out little section for each chunk that is the size of the data and the data in byte[] format.

Done! You just started your day and you've already finished.

This little library takes some code from NAudio.Core as well as WaveLibrary so that it is cross-platform, and allows you to focus on the fun part which is generating wave forms.

Chirp comes with 5 standard waves in the SignalGenerator class. If you want to make your own wave forms, you can inherit from the SignalGenerator class and override the Read(short[] buffer, int count) function. The code for the standard waves is in the source code for the Chirp library and can be found on GitHub at the link above. In short, we are handed a buffer and we fill it up based on the sample rate and duration etc.

The sine wave generation would like something like:

public override int Read(short[] buffer, int count)
   var amplitude = (short) (short.MaxValue * (short) Gain);

   for (uint index = 0; index < count - 1; index++)
      timePeriod = Math.PI * Frequency / WaveFormat.SampleRate;
      sampleValue = Convert.ToInt16(amplitude * Math.Sin(timePeriod * index));
      buffer[index] = sampleValue;

That's it! The rest is up to your imagination.

There is a reference project in Xamarin Forms and blog posts for this library on this site here and here.