-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathAudioSource.cs
More file actions
70 lines (62 loc) · 2.38 KB
/
AudioSource.cs
File metadata and controls
70 lines (62 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.Xna.Framework.Audio;
using System;
namespace AutoPong
{
public class AudioSource
{
private int SampleRate = 48000;
private DynamicSoundEffectInstance DSEI;
private byte[] Buffer;
private int BufferSize;
private int TotalTime = 0;
static Random Rand = new Random();
public AudioSource()
{
DSEI = new DynamicSoundEffectInstance(SampleRate, AudioChannels.Mono);
BufferSize = DSEI.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(500));
Buffer = new byte[BufferSize];
DSEI.Volume = 0.4f;
DSEI.IsLooped = false;
}
public void PlayWave(double freq, short durMS, WaveType Wt, float Volume)
{
DSEI.Stop();
BufferSize = DSEI.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(durMS));
Buffer = new byte[BufferSize];
int size = BufferSize - 1;
for (int i = 0; i < size; i += 2)
{
double time = (double)TotalTime / (double)SampleRate;
short currentSample = 0;
switch (Wt)
{
case WaveType.Sin:
{
currentSample = (short)(Math.Sin(2 * Math.PI * freq * time) * (double)short.MaxValue * Volume);
break;
}
case WaveType.Tan:
{
currentSample = (short)(Math.Tan(2 * Math.PI * freq * time) * (double)short.MaxValue * Volume);
break;
}
case WaveType.Square:
{
currentSample = (short)(Math.Sign(Math.Sin(2 * Math.PI * freq * time)) * (double)short.MaxValue * Volume);
break;
}
case WaveType.Noise:
{
currentSample = (short)(Rand.Next(-short.MaxValue, short.MaxValue) * Volume);
break;
}
}
Buffer[i] = (byte)(currentSample & 0xFF);
Buffer[i + 1] = (byte)(currentSample >> 8);
TotalTime += 2;
}
DSEI.SubmitBuffer(Buffer);
DSEI.Play();
}
}
}