-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
AudioBase.cs
454 lines (378 loc) · 13.7 KB
/
AudioBase.cs
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Runtime.InteropServices;
namespace System.Speech.Internal.Synthesis
{
/// <summary>
/// Encapsulates Waveform Audio Interface playback functions and provides a simple
/// interface for playing audio.
/// </summary>
internal abstract class AudioBase
{
#region Constructors
/// <summary>
/// Create an instance of AudioBase.
/// </summary>
internal AudioBase()
{
}
#endregion
#region Internal Methods
#region abstract Members
/// <summary>
/// Play a wave file.
/// </summary>
internal abstract void Begin(byte[] wfx);
/// <summary>
/// Play a wave file.
/// </summary>
internal abstract void End();
/// <summary>
/// Play a wave file.
/// </summary>
internal virtual void Play(IntPtr pBuff, int cb)
{
byte[] buffer = new byte[cb];
Marshal.Copy(pBuff, buffer, 0, cb);
Play(buffer);
}
/// <summary>
/// Play a wave file.
/// </summary>
internal virtual void Play(byte[] buffer)
{
GCHandle gc = GCHandle.Alloc(buffer);
Play(gc.AddrOfPinnedObject(), buffer.Length);
gc.Free();
}
/// <summary>
/// Pause the playback of a sound.
/// </summary>
internal abstract void Pause();
/// <summary>
/// Resume the playback of a paused sound.
/// </summary>
internal abstract void Resume();
/// <summary>
/// Throw an event synchronized with the audio stream
/// </summary>
internal abstract void InjectEvent(TTSEvent ttsEvent);
/// <summary>
/// File operation are synchronous no wait
/// </summary>
internal abstract void WaitUntilDone();
/// <summary>
/// Wait for all the queued buffers to be played
/// </summary>
internal abstract void Abort();
#endregion
#region helpers
internal void PlayWaveFile(AudioData audio)
{
// allocate some memory for the largest header
try
{
// Fake a header for ALaw and ULaw
if (!string.IsNullOrEmpty(audio._mimeType))
{
WAVEFORMATEX wfx = new();
wfx.nChannels = 1;
wfx.nSamplesPerSec = 8000;
wfx.nAvgBytesPerSec = 8000;
wfx.nBlockAlign = 1;
wfx.wBitsPerSample = 8;
wfx.cbSize = 0;
switch (audio._mimeType)
{
case "audio/basic":
wfx.wFormatTag = (short)AudioFormat.EncodingFormat.ULaw;
break;
case "audio/x-alaw-basic":
wfx.wFormatTag = (short)AudioFormat.EncodingFormat.ALaw;
break;
default:
throw new FormatException(SR.Get(SRID.UnknownMimeFormat));
}
Begin(wfx.ToBytes());
try
{
byte[] data = new byte[(int)audio._stream.Length];
audio._stream.Read(data, 0, data.Length);
Play(data);
}
finally
{
WaitUntilDone();
End();
}
}
else
{
BinaryReader br = new(audio._stream);
try
{
byte[] wfx = GetWaveFormat(br);
if (wfx == null)
{
throw new FormatException(SR.Get(SRID.NotValidAudioFile, audio._uri.ToString()));
}
Begin(wfx);
try
{
while (true)
{
DATAHDR dataHdr = new();
// check for the end of file (+8 for the 2 DWORD)
if (audio._stream.Position + 8 >= audio._stream.Length)
{
break;
}
dataHdr._id = br.ReadUInt32();
dataHdr._len = br.ReadInt32();
// Is this the WAVE data?
if (dataHdr._id == DATA_MARKER)
{
byte[] ab = Helpers.ReadStreamToByteArray(audio._stream, dataHdr._len);
Play(ab);
}
else
{
// Skip this RIFF fragment.
audio._stream.Seek(dataHdr._len, SeekOrigin.Current);
}
}
}
finally
{
WaitUntilDone();
End();
}
}
finally
{
((IDisposable)br).Dispose();
}
}
}
finally
{
audio.Dispose();
}
}
internal static byte[] GetWaveFormat(BinaryReader br)
{
// Read the riff Header
RIFFHDR riff = new();
riff._id = br.ReadUInt32();
riff._len = br.ReadInt32();
riff._type = br.ReadUInt32();
if (riff._id != RIFF_MARKER && riff._type != WAVE_MARKER)
{
return null;
}
BLOCKHDR block = new();
block._id = br.ReadUInt32();
block._len = br.ReadInt32();
if (block._id != FMT_MARKER)
{
return null;
}
// If the format is of type WAVEFORMAT then fake a cbByte with a length of zero
byte[] wfx;
wfx = br.ReadBytes(block._len);
// Hardcode the value of the size for the structure element
// as the C# compiler pads the structure to the closest 4 or 8 bytes
if (block._len == 16)
{
byte[] wfxTemp = new byte[18];
Array.Copy(wfx, wfxTemp, 16);
wfx = wfxTemp;
}
return wfx;
}
internal static void WriteWaveHeader(Stream stream, WAVEFORMATEX waveEx, long position, int cData)
{
RIFFHDR riff = new(0);
BLOCKHDR block = new(0);
DATAHDR dataHdr = new(0);
int cRiff = Marshal.SizeOf<RIFFHDR>();
int cBlock = Marshal.SizeOf<BLOCKHDR>();
int cWaveEx = waveEx.Length;// Marshal.SizeOf (waveEx); // The CLR automatically pad the waveEx structure to dword boundary. Force 16.
int cDataHdr = Marshal.SizeOf<DATAHDR>();
int total = cRiff + cBlock + cWaveEx + cDataHdr;
using (MemoryStream memStream = new())
{
BinaryWriter bw = new(memStream);
try
{
// Write the RIFF section
riff._len = total + cData - 8/* - cRiff*/; // for the "WAVE" 4 characters
bw.Write(riff._id);
bw.Write(riff._len);
bw.Write(riff._type);
// Write the wave header section
block._len = cWaveEx;
bw.Write(block._id);
bw.Write(block._len);
// Write the FormatEx structure
bw.Write(waveEx.ToBytes());
//bw.Write (waveEx.cbSize);
// Write the data section
dataHdr._len = cData;
bw.Write(dataHdr._id);
bw.Write(dataHdr._len);
stream.Seek(position, SeekOrigin.Begin);
stream.Write(memStream.GetBuffer(), 0, (int)memStream.Length);
}
finally
{
((IDisposable)bw).Dispose();
}
}
}
#endregion
#endregion
#region Internal Property
internal abstract TimeSpan Duration { get; }
internal virtual long Position { get { return 0; } }
internal virtual bool IsAborted
{
get
{
return _aborted;
}
set
{
_aborted = false;
}
}
internal virtual byte[] WaveFormat { get { return null; } }
#endregion
#region Protected Property
protected bool _aborted;
#endregion
#region Private Types
private const uint RIFF_MARKER = 0x46464952;
private const uint WAVE_MARKER = 0x45564157;
private const uint FMT_MARKER = 0x20746d66;
private const uint DATA_MARKER = 0x61746164;
[StructLayout(LayoutKind.Sequential)]
private struct RIFFHDR
{
internal uint _id;
internal int _len; /* file length less header */
internal uint _type; /* should be "WAVE" */
internal RIFFHDR(int length)
{
_id = RIFF_MARKER;
_type = WAVE_MARKER;
_len = length;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct BLOCKHDR
{
internal uint _id; /* should be "fmt " or "data" */
internal int _len; /* block size less header */
internal BLOCKHDR(int length)
{
_id = FMT_MARKER;
_len = length;
}
};
[StructLayout(LayoutKind.Sequential)]
private struct DATAHDR
{
internal uint _id; /* should be "fmt " or "data" */
internal int _len; /* block size less header */
internal DATAHDR(int length)
{
_id = DATA_MARKER;
_len = length;
}
}
#endregion
}
#region Internal Methods
[System.Runtime.InteropServices.TypeLibTypeAttribute(16)]
internal struct WAVEFORMATEX
{
internal short wFormatTag;
internal short nChannels;
internal int nSamplesPerSec;
internal int nAvgBytesPerSec;
internal short nBlockAlign;
internal short wBitsPerSample;
internal short cbSize;
internal static WAVEFORMATEX ToWaveHeader(byte[] waveHeader)
{
GCHandle gc = GCHandle.Alloc(waveHeader, GCHandleType.Pinned);
IntPtr ptr = gc.AddrOfPinnedObject();
WAVEFORMATEX wfx = new();
wfx.wFormatTag = Marshal.ReadInt16(ptr);
wfx.nChannels = Marshal.ReadInt16(ptr, 2);
wfx.nSamplesPerSec = Marshal.ReadInt32(ptr, 4);
wfx.nAvgBytesPerSec = Marshal.ReadInt32(ptr, 8);
wfx.nBlockAlign = Marshal.ReadInt16(ptr, 12);
wfx.wBitsPerSample = Marshal.ReadInt16(ptr, 14);
wfx.cbSize = Marshal.ReadInt16(ptr, 16);
if (wfx.cbSize != 0)
{
throw new InvalidOperationException();
}
gc.Free();
return wfx;
}
internal static void AvgBytesPerSec(byte[] waveHeader, out int avgBytesPerSec, out int nBlockAlign)
{
// Hardcode the value of the size for the structure element
// as the C# compiler pads the structure to the closest 4 or 8 bytes
GCHandle gc = GCHandle.Alloc(waveHeader, GCHandleType.Pinned);
IntPtr ptr = gc.AddrOfPinnedObject();
avgBytesPerSec = Marshal.ReadInt32(ptr, 8);
nBlockAlign = Marshal.ReadInt16(ptr, 12);
gc.Free();
}
internal byte[] ToBytes()
{
System.Diagnostics.Debug.Assert(cbSize == 0);
GCHandle gc = GCHandle.Alloc(this, GCHandleType.Pinned);
byte[] ab = ToBytes(gc.AddrOfPinnedObject());
gc.Free();
return ab;
}
internal static byte[] ToBytes(IntPtr waveHeader)
{
// Hardcode the value of the size for the structure element
// as the C# compiler pads the structure to the closest 4 or 8 bytes
int cbSize = Marshal.ReadInt16(waveHeader, 16);
byte[] ab = new byte[18 + cbSize];
Marshal.Copy(waveHeader, ab, 0, 18 + cbSize);
return ab;
}
internal static WAVEFORMATEX Default
{
get
{
WAVEFORMATEX wfx = new();
wfx.wFormatTag = 1;
wfx.nChannels = 1;
wfx.nSamplesPerSec = 22050;
wfx.nAvgBytesPerSec = 44100;
wfx.nBlockAlign = 2;
wfx.wBitsPerSample = 16;
wfx.cbSize = 0;
return wfx;
}
}
internal int Length
{
get
{
return 18 + cbSize;
}
}
}
#endregion
}