-
Notifications
You must be signed in to change notification settings - Fork 6
/
WaveFile.cs
588 lines (511 loc) · 21.1 KB
/
WaveFile.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ReadWave
{
public class WaveStream
{
public static double bytesToDouble(byte firstByte, byte secondByte)
{
short s = (short)((secondByte << 8) | firstByte);
return s / 32768.0;
}
public static byte[] DoubleToBytes(double d)
{
d = d * 32768.0;
short s = (short)d;
return new byte[] { (byte)(s), (byte)(s >> 8) };
}
public static byte[] StrToByteArray(String pStr)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(pStr);
}
// if mono left only
public static void ReadWavFile(string filename, out int channels, out int sampleRate, out int bitDepth, out double[] left, out double[] right)
{
left = right = null;
byte[] wav = File.ReadAllBytes(filename);
Int16[] I2 = new Int16[1];
Single[] F4 = new Single[1];
Int32[] I4 = new Int32[1];
System.Buffer.BlockCopy(wav, 22, I2, 0, 2);
channels = I2[0];
System.Buffer.BlockCopy(wav, 24, I4, 0, 4);
sampleRate = I4[0];
System.Buffer.BlockCopy(wav, 34, I2, 0, 2);
bitDepth = I2[0];
// Get past all the other sub chunks to get to the data subchunk:
int pos = 12; // First Subchunk ID from 12 to 16
// Keep iterating until we find the `data` chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
while (!(wav[pos] == 100 && wav[pos + 1] == 97 && wav[pos + 2] == 116 && wav[pos + 3] == 97))
{
pos += 4;
int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
pos += 4 + chunkSize;
};
pos += 4; // `data`
System.Buffer.BlockCopy(wav, pos, I4, 0, 4);
int ttlbytes = I4[0];
int bytesForSamp = bitDepth / 8;
int samples = ttlbytes / bytesForSamp;
int sampchl = channels == 2 ? samples / 2 : samples;
pos += 4; // samples bytes length
// Pos is now positioned to start of actual sound data.
left = new double[sampchl];
if (channels == 2) right = new double[sampchl];
// Read samples
for (int i = 0; i < sampchl; i++)
{
bool leftCH = true;
double[] F8 = left;
while (true)
{
switch (bitDepth)
{
case 64:
System.Buffer.BlockCopy(wav, pos, F8, i, 8);
pos += 8;
break;
case 32:
System.Buffer.BlockCopy(wav, pos, F4, 0, 4);
pos += 4;
F8[i] = F4[0];
break;
case 16:
System.Buffer.BlockCopy(wav, pos, I2, 0, 2);
F8[i] = I2[0] / 32768.0;
pos += 2;
break;
};
if (leftCH && (channels == 2))
{
leftCH = false;
F8 = right;
}
else
break;
};
};
}
// if mono left only
public static void ReadWavFile(string filename, out int channels, out int sampleRate, out int bitDepth, out float[] left, out float[] right)
{
left = right = null;
byte[] wav = File.ReadAllBytes(filename);
Int16[] I2 = new Int16[1];
Single[] F4 = new Single[1];
Int32[] I4 = new Int32[1];
System.Buffer.BlockCopy(wav, 22, I2, 0, 2);
channels = I2[0];
System.Buffer.BlockCopy(wav, 24, I4, 0, 4);
sampleRate = I4[0];
System.Buffer.BlockCopy(wav, 34, I2, 0, 2);
bitDepth = I2[0];
// Get past all the other sub chunks to get to the data subchunk:
int pos = 12; // First Subchunk ID from 12 to 16
// Keep iterating until we find the `data` chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
while (!(wav[pos] == 100 && wav[pos + 1] == 97 && wav[pos + 2] == 116 && wav[pos + 3] == 97))
{
pos += 4;
int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
pos += 4 + chunkSize;
};
pos += 4; // `data`
System.Buffer.BlockCopy(wav, pos, I4, 0, 4);
int ttlbytes = I4[0];
int bytesForSamp = bitDepth / 8;
int samples = ttlbytes / bytesForSamp;
int sampchl = channels == 2 ? samples / 2 : samples;
pos += 4; // samples bytes length
// Pos is now positioned to start of actual sound data.
left = new float[sampchl];
if (channels == 2) right = new float[sampchl];
// Read samples
for (int i = 0; i < sampchl; i++)
{
bool leftCH = true;
F4 = left;
while (true)
{
switch (bitDepth)
{
case 64:
double[] F8 = new double[1];
System.Buffer.BlockCopy(wav, pos, F8, 0, 8);
F4[i] = (float)F8[0];
pos += 8;
break;
case 32:
System.Buffer.BlockCopy(wav, pos, F4, i, 4);
pos += 4;
break;
case 16:
System.Buffer.BlockCopy(wav, pos, I2, 0, 2);
F4[i] = (float)(I2[0] / 32768.0);
pos += 2;
break;
};
if (leftCH && (channels == 2))
{
leftCH = false;
F4 = right;
}
else
break;
};
};
}
public static void WriteWavHeader(Stream stream, bool isFloatingPoint, ushort channelCount, ushort bitDepth, int sampleRate, int totalSampleCount)
{
stream.Position = 0;
// RIFF header.
// Chunk ID.
stream.Write(Encoding.ASCII.GetBytes("RIFF"), 0, 4);
// Chunk size.
stream.Write(BitConverter.GetBytes(((bitDepth / 8) * totalSampleCount) + 36), 0, 4);
// Format.
stream.Write(Encoding.ASCII.GetBytes("WAVE"), 0, 4);
// Sub-chunk 1.
// Sub-chunk 1 ID.
stream.Write(Encoding.ASCII.GetBytes("fmt "), 0, 4);
// Sub-chunk 1 size.
stream.Write(BitConverter.GetBytes(16), 0, 4);
// Audio format (floating point (3) or PCM (1)). Any other format indicates compression.
stream.Write(BitConverter.GetBytes((ushort)(isFloatingPoint ? 3 : 1)), 0, 2);
// Channels.
stream.Write(BitConverter.GetBytes(channelCount), 0, 2);
// Sample rate.
stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);
// Bytes rate.
stream.Write(BitConverter.GetBytes(sampleRate * channelCount * (bitDepth / 8)), 0, 4);
// Block align.
stream.Write(BitConverter.GetBytes((ushort)channelCount * (bitDepth / 8)), 0, 2);
// Bits per sample.
stream.Write(BitConverter.GetBytes(bitDepth), 0, 2);
// Sub-chunk 2.
// Sub-chunk 2 ID.
stream.Write(Encoding.ASCII.GetBytes("data"), 0, 4);
// Sub-chunk 2 size.
stream.Write(BitConverter.GetBytes((bitDepth / 8) * totalSampleCount), 0, 4);
}
public static void WriteWav16BitMono(Stream stream, int sampleRate, float[] samples)
{
WriteWavHeader(stream, false, 1, 16, sampleRate, samples.Length);
List<byte> ba = new List<byte>();
{
for (int i = 0; i < samples.Length; i++)
{
byte[] fs = WaveStream.DoubleToBytes(samples[i]);
ba.AddRange(fs);
};
};
stream.Write(ba.ToArray(), 0, ba.Count);
}
public static void SaveWav16BitMono(string filename, int sampleRate, float[] samples)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitMono(fs, sampleRate, samples);
fs.Close();
}
public static void WriteWav16BitMono(Stream stream, int sampleRate, double[] samples)
{
WriteWavHeader(stream, false, 1, 16, sampleRate, samples.Length);
List<byte> ba = new List<byte>();
{
for (int i = 0; i < samples.Length; i++)
{
byte[] fs = WaveStream.DoubleToBytes(samples[i]);
ba.AddRange(fs);
};
};
stream.Write(ba.ToArray(), 0, ba.Count);
}
public static void SaveWav16BitMono(string filename, int sampleRate, double[] samples)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitMono(fs, sampleRate, samples);
fs.Close();
}
public static void WriteWav16BitStereo(Stream stream, int sampleRate, float[] L, float[] R)
{
WriteWavHeader(stream, false, 2, 16, sampleRate, L.Length * 2);
List<byte> ba = new List<byte>();
{
for (int i = 0; i < L.Length; i++)
{
byte[] fs = WaveStream.DoubleToBytes(L[i]);
ba.AddRange(fs);
fs = WaveStream.DoubleToBytes(R[i]);
ba.AddRange(fs);
};
};
stream.Write(ba.ToArray(), 0, ba.Count);
}
public static void SaveWav16BitStereo(string filename, int sampleRate, float[] L, float[] R)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitStereo(fs, sampleRate, L, R);
fs.Close();
}
public static void WriteWav16BitStereo(Stream stream, int sampleRate, double[] L, double[] R)
{
WriteWavHeader(stream, false, 2, 16, sampleRate, L.Length * 2);
List<byte> ba = new List<byte>();
{
for (int i = 0; i < L.Length; i++)
{
byte[] fs = WaveStream.DoubleToBytes(L[i]);
ba.AddRange(fs);
fs = WaveStream.DoubleToBytes(R[i]);
ba.AddRange(fs);
};
};
stream.Write(ba.ToArray(), 0, ba.Count);
}
public static void SaveWav16BitStereo(string filename, int sampleRate, double[] L, double[] R)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitStereo(fs, sampleRate, L, R);
fs.Close();
}
public static void WriteWav16BitStereo(Stream stream, int sampleRate, float[] mono)
{
WriteWav16BitStereo(stream, sampleRate, mono, mono);
}
public static void SaveWav16BitStereo(string filename, int sampleRate, float[] mono)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitStereo(fs, sampleRate, mono);
fs.Close();
}
public static void WriteWav16BitStereo(Stream stream, int sampleRate, double[] mono)
{
WriteWav16BitStereo(stream, sampleRate, mono, mono);
}
public static void SaveWav16BitStereo(string filename, int sampleRate, double[] mono)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
WriteWav16BitStereo(fs, sampleRate, mono);
fs.Close();
}
public static void PlaySamples(int sampleRate, float[] mono, bool wait)
{
MemoryStream ms = new MemoryStream();
WriteWav16BitMono(ms, sampleRate, mono);
PlayStream(ms, wait, true);
}
public static void PlaySamples(int sampleRate, double[] mono, bool wait)
{
MemoryStream ms = new MemoryStream();
WriteWav16BitMono(ms, sampleRate, mono);
PlayStream(ms, wait, true);
}
public static void PlaySamples(int sampleRate, float[] left, float[] right, bool wait)
{
MemoryStream ms = new MemoryStream();
WriteWav16BitStereo(ms, sampleRate, left, right);
PlayStream(ms, wait, true);
}
public static void PlaySamples(int sampleRate, double[] left, double[] right, bool wait)
{
MemoryStream ms = new MemoryStream();
WriteWav16BitStereo(ms, sampleRate, left, right);
PlayStream(ms, wait, true);
}
public static void PlayStream(Stream stream, bool wait, bool closeStream)
{
stream.Position = 0;
if (wait)
{
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
if (closeStream)
{
wfr.Close();
stream.Close();
stream = null;
};
}
else
{
System.Threading.Thread thr = new System.Threading.Thread(Play);
thr.Start(new object[] { stream, closeStream });
};
}
public static void PlayFile(string filename, bool wait)
{
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
if (wait)
{
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
wfr.Close();
stream.Close();
}
else
{
System.Threading.Thread thr = new System.Threading.Thread(Play);
thr.Start(new object[] { stream, true });
};
}
private static void Play(object stream_close)
{
object[] strmcls = (object[])stream_close;
Stream stream = (Stream)strmcls[0];
bool closeStream = (bool)strmcls[1];
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
if (closeStream)
{
wfr.Close();
stream.Close();
stream = null;
};
}
}
public class WavePlayer
{
private int dev = 0;
private float vol = -1;
public WavePlayer() {}
public WavePlayer(float Volume)
{
this.vol = Volume;
}
public WavePlayer(int DeviceNo)
{
this.dev = DeviceNo;
}
public WavePlayer(int DeviceNo, float Volume)
{
this.dev = DeviceNo;
this.vol = Volume;
}
public int DeviceNo
{
get { return dev; }
set { dev = value; }
}
public float Volume
{
get
{
if (vol == -1)
{
NAudio.Wave.WaveOutEvent woe = new NAudio.Wave.WaveOutEvent();
woe.DeviceNumber = dev;
return woe.Volume;
}
else
return vol;
}
set { vol = value; }
}
public void PlaySamples(int sampleRate, float[] mono, bool wait)
{
MemoryStream ms = new MemoryStream();
WaveStream.WriteWav16BitMono(ms, sampleRate, mono);
PlayStream(ms, wait, true);
}
public void PlaySamples(int sampleRate, double[] mono, bool wait)
{
MemoryStream ms = new MemoryStream();
WaveStream.WriteWav16BitMono(ms, sampleRate, mono);
PlayStream(ms, wait, true);
}
public void PlaySamples(int sampleRate, float[] left, float[] right, bool wait)
{
MemoryStream ms = new MemoryStream();
WaveStream.WriteWav16BitStereo(ms, sampleRate, left, right);
PlayStream(ms, wait, true);
}
public void PlaySamples(int sampleRate, double[] left, double[] right, bool wait)
{
MemoryStream ms = new MemoryStream();
WaveStream.WriteWav16BitStereo(ms, sampleRate, left, right);
PlayStream(ms, wait, true);
}
public void PlayStream(Stream stream, bool wait, bool closeStream)
{
stream.Position = 0;
if (wait)
{
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.DeviceNumber = dev;
if (vol != -1) wo.Volume = vol;
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
if (closeStream)
{
wfr.Close();
stream.Close();
stream = null;
};
}
else
{
System.Threading.Thread thr = new System.Threading.Thread(Play);
thr.Start(new object[] { stream, closeStream });
};
}
public void PlayFile(string filename, bool wait)
{
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
if (wait)
{
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.DeviceNumber = dev;
if (vol != -1) wo.Volume = vol;
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
wfr.Close();
stream.Close();
}
else
{
System.Threading.Thread thr = new System.Threading.Thread(Play);
thr.Start(new object[] { stream, true });
};
}
private void Play(object stream_close)
{
object[] strmcls = (object[])stream_close;
Stream stream = (Stream)strmcls[0];
bool closeStream = (bool)strmcls[1];
NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(stream);
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
wo.DeviceNumber = dev;
if (vol != -1) wo.Volume = vol;
wo.Init(wfr);
wo.Play();
while (wo.PlaybackState == NAudio.Wave.PlaybackState.Playing)
System.Threading.Thread.Sleep(10);
if (closeStream)
{
wfr.Close();
stream.Close();
stream = null;
};
}
}
}