Play dynamically-created simple sounds in C# without external libraries

Viewed 6976

I need to be able to generate dynamically a waveform and play it, using C#, without any external libraries, and without having to store sound files on the hard disk. Latency isn't an issue; the sounds would be generated well before they are needed by the application.

Actually the Console.Beep() method might meet my needs if it weren't for the fact that Microsoft says it isn't supported in 64-bit versions of Windows.

If I generate my own sound dynamically I can get a more fancy than a simple beep. For example, I could make a waveform from a triangle wave that increases in frequency from 2 KHz to 4 KHz while decaying in volume. I don't need fancy 16-bit stereo, just 8-bit mono is fine. I don't need dynamic control over volume and pitch, just basically generate a soundfile in memory and play it without storing it.

Last time I needed to generate sounds was many years ago, on Apple II, on HP workstations, and on my old Amiga computer. Haven't needed to do it since then, and it seems that something simple that I describe has gotten a lot more complicated. I am having trouble believing that something so simple seems so hard. Most of the answers I see refer to NAudio or similar libraries, and that isn't an option for this project (aside from the fact that pulling in an entire library just to play a tone seems like a waste).

3 Answers

I tried out the code-snipped from Anachronist (2012-10) - and it is working for me.

biggest hurdle for me: get rid of the systematic "clicking-noise" at the end of "AlertDing" wav.

This is caused by a "soft-bug" in the code snipped:

for (uint i = 0; i < numSamples - 1; i += fmt_Channels)

needs to change to

for (uint i = 0; i < numSamples; i += fmt_Channels)

if not changed, a systematic "zero" will be generated at the end of each "play", causing a sharp clicking noise. (= amplitude jumps 0->min->0)

the original question implies "without clicking noise" of course :)

Related