I am learning while doing a little mobile app with C#, in the book I am following there is a part where a triangular wave is generated and I want to change it to a Sine, but I can not figure out how to apply the mathematical sine wave formula to get each sample at (say) 16 bits with a normalized 0 - 1 amplitude and at 44.1Khz.
The audio library expects a buffer with that data, can someone please point me in the right direction?
Thanks!
pd: Just in case, the code used for the triangle wave is:
Code: Select all
class SoundPlayer
{
const int sampleRate = 44100;
// Hard-coded for monaural, 16-bit-per-sample PCM
public static void PlaySound(double frequency = 440, int duration = 250)
{
short[] shortBuffer = new short[sampleRate * duration / 1000];
double angleIncrement = frequency / sampleRate;
double angle = 0; // normalized 0 to 1
for (int i = 0; i < shortBuffer.Length; i++)
{
// Define triangle wave
double sample;
// 0 to 1
if (angle < 0.25)
sample = 4 * angle;
// 1 to -1
else if (angle < 0.75)
sample = 4 * (0.5 - angle);
// -1 to 0
else
sample = 4 * (angle - 1);
shortBuffer[i] = (short)(32767 * sample);
angle += angleIncrement;
while (angle > 1)
angle -= 1;
}
byte[] byteBuffer = new byte[2 * shortBuffer.Length];
Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, byteBuffer.Length);
DependencyService.Get<IPlatformSoundPlayer>().PlaySound(sampleRate, byteBuffer);
}
}