Search code examples
c#audiowaveform

How to make an audio stream in C#? (general)


I have been doing a synthesizer project on Atmel microcontrollers using C++, but I had a lack of knowledge on timing, because ctime library is using integer millisecond parameters (if it would even work on Atmel), but I have a need to output (for example) a square wave with frequencies up to 44100Hz, which, obviously, changes output state from -1 to 1 with periods that are 88.2 times shorter than a millisecond.

Now I am learning to build PC audio applications using C#. So, there are my questions:

  1. How would you time app to do something exactly 1/88.2 ms in C#, using, for example, time comparing function and only native libraries (if that is actually possible)?
  2. How could you output your steam (for example 1 and -1 values with any loudness) to your PC's sound device?

Solution

  • Normally PC audio devices require you to send PCM packets in specific buffer sizes (for example 200ms).

    For a sample rate of 44100, you put 11025 Samples (per channel) in a buffer and send it to the audio device via an API such as DirectSound for which managed libraries exist. Alternatively you can use the Windows Core Audi API directly. There are many others.

    No need to control each sample individually.

    A Sample can be anything from a list of 8/16/24/32/64 bits and is stored in a specific data type, such as:

    • unsigned byte for 8 bit samples
    • short or Int16 for 16 bits samples
    • C# does not support 24 bit integers natively
    • Int32 or float for 32 bit samples
    • etc.

    Essentlially you have to tell your audio device how many samples (SampleRate) of what type (SampleSize) on how many channels (ChannelNum) you'll send it, agree on a buffer size and go!