-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioPlayer.cs
More file actions
256 lines (210 loc) · 7.66 KB
/
AudioPlayer.cs
File metadata and controls
256 lines (210 loc) · 7.66 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using OpenTK.Audio.OpenAL;
using SoundSources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AudioPlayer
{
/// <summary>
///
/// AudioDevice (OpenAL)
///
/// </summary>
public class AudioDevice : IDisposable
{
private ALDevice _device;
private ALContext _context;
public AudioDevice()
{
// Открываем устройство
_device = ALC.OpenDevice(null);
if (_device == ALDevice.Null)
throw new Exception("Failed to open default audio device.");
// Создаём контекст
ALContextAttributes attrs = new ALContextAttributes();
_context = ALC.CreateContext(_device, attrs);
if (_context == ALContext.Null)
throw new Exception("Failed to create OpenAL context.");
// Активируем
ALC.MakeContextCurrent(_context);
}
public void Dispose()
{
ALC.MakeContextCurrent(ALContext.Null);
if (_context != ALContext.Null)
{
ALC.DestroyContext(_context);
_context = ALContext.Null;
}
if (_device != ALDevice.Null)
{
ALC.CloseDevice(_device);
_device = ALDevice.Null;
}
}
}
/// <summary>
/// AudioMixer
/// </summary>
public class AudioMixer : IDisposable
{
private AudioDevice _audioDevice;
private int _source;
private Queue<int> _buffersQueue = new Queue<int>();
// Храним список SoundSource
private List<SoundSource> _sources = new List<SoundSource>();
// Внутренние
private float _currentTime = 0f;
private int _sampleRate;
private int _bufferSize;
// WAV запись
private MemoryStream _wavMem;
private BinaryWriter _wavWriter;
private int _totalSamplesWritten;
public string OutputWavFile { get; set; } = "result.wav";
public AudioMixer(int sampleRate = 44100, int bufferSize = 1024)
{
_sampleRate = sampleRate;
_bufferSize = bufferSize;
// 1) Создаём аудиоустройство
_audioDevice = new AudioDevice();
// 2) Генерируем источник
_source = AL.GenSource();
// 3) Подготовим WAV
_wavMem = new MemoryStream();
_wavWriter = new BinaryWriter(_wavMem);
WriteWavHeaderPlaceholder();
}
public void AddSoundSource(SoundSource src)
{
_sources.Add(src);
}
public void RemoveSoundSource(SoundSource src)
{
_sources.Remove(src);
}
/// <summary>
/// Вызывать каждые ~10 мс. Генерирует bufferSize сэмплов,
/// проигрывает их через OpenAL, параллельно пишет в WAV.
/// </summary>
public void Update()
{
// Генерируем samples
short[] samples = new short[_bufferSize];
for (int i = 0; i < _bufferSize; i++)
{
float mixed = 0f;
// Суммируем по всем SoundSource
foreach (var src in _sources)
{
mixed += src.GenerateSample(_currentTime);
}
samples[i] = FloatToShort(mixed);
_currentTime += 1f / _sampleRate;
}
// Проигрываем в OpenAL
int bufferId = AL.GenBuffer();
ALFormat format = ALFormat.Mono16;
unsafe
{
fixed (short* ptr = samples)
{
AL.BufferData(bufferId, format, (IntPtr)ptr, samples.Length * sizeof(short), _sampleRate);
}
}
AL.SourceQueueBuffer(_source, bufferId);
_buffersQueue.Enqueue(bufferId);
// Запуск, если не играет
AL.GetSource(_source, ALGetSourcei.SourceState, out int state);
if ((ALSourceState)state != ALSourceState.Playing)
{
AL.SourcePlay(_source);
}
// Удаляем отыгранные буферы
AL.GetSource(_source, ALGetSourcei.BuffersProcessed, out int processed);
while (processed-- > 0)
{
int oldBuf = AL.SourceUnqueueBuffer(_source);
AL.DeleteBuffer(oldBuf);
_buffersQueue.Dequeue();
}
// Записываем в WAV
WriteToWav(samples);
// Удаляем просроченные компоненты, источники
Cleanup();
}
private void Cleanup()
{
// 1) Удаляем просроченные компоненты
foreach (var src in _sources)
{
src.RemoveExpiredComponents(_currentTime);
}
// 2) Удаляем сами SoundSource, если помечены и пусты
_sources.RemoveAll(s => s.CanBeRemoved());
}
public void Dispose()
{
// Останавливаем
AL.SourceStop(_source);
// Удаляем все буферы
while (_buffersQueue.Count > 0)
{
int b = _buffersQueue.Dequeue();
AL.DeleteBuffer(b);
}
AL.DeleteSource(_source);
_wavWriter.Close();
_wavMem.Close();
// Освобождаем аудиоустройство
_audioDevice.Dispose();
}
public void SaveWav()
{
// Завершаем WAV
FinalizeWav();
File.WriteAllBytes(OutputWavFile, _wavMem.ToArray());
}
// ---- Вспомогательное: WAV ----
private void WriteWavHeaderPlaceholder()
{
byte[] blank = new byte[44];
_wavWriter.Write(blank);
}
private void WriteToWav(short[] samples)
{
foreach (var s in samples)
_wavWriter.Write(s);
_totalSamplesWritten += samples.Length;
}
private void FinalizeWav()
{
_wavWriter.Seek(0, SeekOrigin.Begin);
int subchunk2Size = _totalSamplesWritten * sizeof(short);
int chunkSize = 36 + subchunk2Size;
_wavWriter.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));
_wavWriter.Write(chunkSize);
_wavWriter.Write(System.Text.Encoding.ASCII.GetBytes("WAVE"));
_wavWriter.Write(System.Text.Encoding.ASCII.GetBytes("fmt "));
_wavWriter.Write(16); // size
_wavWriter.Write((short)1); // PCM
_wavWriter.Write((short)1); // mono
_wavWriter.Write(_sampleRate);
int byteRate = _sampleRate * sizeof(short);
_wavWriter.Write(byteRate);
short blockAlign = (short)sizeof(short);
_wavWriter.Write(blockAlign);
short bitsPerSample = 16;
_wavWriter.Write(bitsPerSample);
_wavWriter.Write(System.Text.Encoding.ASCII.GetBytes("data"));
_wavWriter.Write(subchunk2Size);
}
private short FloatToShort(float val)
{
val = Math.Clamp(val, -1f, 1f);
return (short)(val * short.MaxValue);
}
}
}