In this post I want to show how to create an easy sine generator in .NET.
Let’s start with a code listing and then I’ll explain what I’m doing here:
const double frequency = 1000; const double amplitude = 20000; const long sampleRate = 44100; const int durationSec = 5; long sampleCount = sampleRate * durationSec; double timeStep = 1.0 / (double)sampleRate; double time = 0; int[] values = new int[sampleCount]; for (long i = 0; i < sampleCount; i++) { values[i] = (int)(amplitude * Math.Sin(2 * Math.PI * frequency * time)); time = time + timeStep; }
OK, here are some explanations:
- lines 1-4: some constants you can change to e. g. adjust the frequency.
Note: the frequency cannot be more than half the sampling rate. - line 6: calculating the number of sampling points.
- line 8: calculating the time between two sampling points.
- lines 10-11: some variable initializations.
- lines 12-15: here finally the value of each sampling point is calculated.
And here is the corresponding code for Visual Basic .NET:
const frequency as double = 1000 const amplitude as double = 20000 const sampleRate As Long = 44100 const durationSec As Integer = 5 Dim sampleCount As Long sampleCount = sampleRate * durationSec Dim timeStep As Double timeStep = 1.0 / sampleRate Dim time As Double = 0 Dim values(0 To sampleCount - 1) As Integer For i As Long = 0 To sampleCount - 1 values(i) = amplitude * Math.Sin(2 * Math.PI * frequency * time) time = time + timeStep Next i
For sound playback you can now use either an API call like PlaySound (of winmm.dll) or the solution of this great article.
Did you also need to generate a sine in .NET yourself already?
This post is also available in Deutsch.