-
Notifications
You must be signed in to change notification settings - Fork 29
/
wave.go
1460 lines (1245 loc) · 33.8 KB
/
wave.go
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package wave
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
)
/*
* Global constants.
*/
const (
BITS_PER_BYTE = 8
MIN_CHUNK_HEADER_SIZE = 8
MIN_DATASIZE_CHUNK_SIZE = 28
LENGTH_DATASIZE_TABLE_ENTRIES = 12
)
/*
* Constants for handling of 24-bit integers.
*/
const (
MAX_INT24 = 0x007fffff // int32
MIN_INT24 = -(MAX_INT24 + 1) // int32
SIGN_BIT_INT24 = 0x00800000 // int32
SIZE_INT24 = 3
)
/*
* RIFF header constants.
*/
const (
AUDIO_PCM = 0x0001 // uint16
AUDIO_IEEE_FLOAT = 0x0003 // uint16
DEFAULT_BIT_DEPTH = 0x0010 // uint16
FORMAT_WAVE = 0x45564157 // uint32
ID_BW64 = 0x34365742 // uint32
ID_DATA = 0x61746164 // uint32
ID_DATASIZE = 0x34367364 // uint32
ID_FORMAT = 0x20746d66 // uint32
ID_RIFF = 0x46464952 // uint32
ID_RIFF64 = 0x34364652 // uint32
MIN_CHUNK_SIZE_FORMAT = 0x00000010 // uint32
MIN_TOTAL_HEADER_SIZE = 0x0000002c // uint32
)
/*
* An interface type representing the channels inside a RIFF wave file.
*/
type Channel interface {
Clear()
Floats() []float64
WriteFloats(samples []float64)
}
/*
* The internal data structure representing a channel of a RIFF wave file.
*/
type channelStruct struct {
samples []float64
}
/*
* An interface type representing a RIFF wave file.
*/
type File interface {
BitDepth() uint16
Bytes() ([]byte, error)
Channel(id uint16) (Channel, error)
ChannelCount() uint16
SampleFormat() uint16
SampleRate() uint32
}
/*
* The internal data structure representing a RIFF wave file.
*/
type fileStruct struct {
bitDepth uint16
sampleFormat uint16
sampleRate uint32
channels []Channel
}
/*
* The structure of a wave file's RIFF header.
*/
type riffHeader struct {
ChunkID uint32
ChunkSize uint32
Format uint32
}
/*
* The structure of a wave file's data size header.
*/
type dataSizeHeader struct {
ChunkID uint32
ChunkSize uint32
SizeRIFF uint64
SizeData uint64
SampleCount uint64
TableLength uint32
}
/*
* The structure of a chunk header for pre-parsing.
*/
type chunkHeader struct {
ChunkID uint32
ChunkSize uint32
}
/*
* The structure of a wave file's format header.
*/
type formatHeader struct {
ChunkID uint32
ChunkSize uint32
AudioFormat uint16
ChannelCount uint16
SampleRate uint32
ByteRate uint32
BlockAlign uint16
BitDepth uint16
}
/*
* The structure of a wave file's data header.
*/
type dataHeader struct {
ChunkID uint32
ChunkSize uint32
}
/*
* Clears all samples from the channel.
*/
func (this *channelStruct) Clear() {
this.samples = make([]float64, 0)
}
/*
* Returns all samples inside this channel in floating-point representation.
*/
func (this *channelStruct) Floats() []float64 {
size := len(this.samples)
samples := make([]float64, size)
copy(samples, this.samples)
return samples
}
/*
* Writes (appends) samples in floating-point representation to this channel.
*/
func (this *channelStruct) WriteFloats(samples []float64) {
this.samples = append(this.samples, samples...)
}
/*
* Utility function for creating an empty buffer.
*/
func createBuffer() *bytes.Buffer {
buf := bytes.Buffer{}
return &buf
}
/*
* Converts a slice of channels into a slice of samples.
*/
func channelsToSamples(channels []Channel) []float64 {
channelCount := len(channels)
channelCount16 := uint16(channelCount)
channelCount32 := uint32(channelCount)
samplesByChannel := make([][]float64, channelCount)
maxSampleCount := uint32(0)
/*
* Iterate over all channels and extract the samples for each.
*/
for i, currentChannel := range channels {
currentSamples := currentChannel.Floats()
sampleCount := len(currentSamples)
sampleCount32 := uint32(sampleCount)
samplesByChannel[i] = currentSamples
/*
* If we found a channel with more samples, make its sample
* count the new longest channel sample count.
*/
if sampleCount32 > maxSampleCount {
maxSampleCount = sampleCount32
}
}
totalSampleCount := channelCount32 * maxSampleCount
data := make([]float64, totalSampleCount)
/*
* Iterate over the samples to reorder them by time.
*/
for i := uint32(0); i < maxSampleCount; i++ {
/*
* Iterate over the channels and extract the current sample.
*/
for j := uint16(0); j < channelCount16; j++ {
currentChannel := samplesByChannel[j]
currentChannelLength := len(currentChannel)
currentChannelLength32 := uint32(currentChannelLength)
currentSample := float64(0.0)
/*
* If the channel is long enough, read the sample from it,
* otherwise pad with zeroes.
*/
if i < currentChannelLength32 {
currentSample = currentChannel[i]
}
j32 := uint32(j)
offset := (channelCount32 * i) + j32
data[offset] = currentSample
}
}
return data
}
/*
* Converts a slice of samples into a slice of channels.
*/
func samplesToChannels(samples []float64, channelCount uint16) []Channel {
channels := make([]Channel, channelCount)
channelCount32 := uint32(channelCount)
size := len(samples)
size32 := uint32(size)
samplesPerChannel := size32 / channelCount32
/*
* Extract each channel from the sample data.
*/
for i := uint16(0); i < channelCount; i++ {
currentSamples := make([]float64, samplesPerChannel)
i32 := uint32(i)
/*
* Extract each sample for this channel.
*/
for j := uint32(0); j < samplesPerChannel; j++ {
idx := (j * channelCount32) + i32
currentSamples[j] = samples[idx]
}
/*
* Data structure representing this channel.
*/
channel := channelStruct{
samples: currentSamples,
}
channels[i] = &channel
}
return channels
}
/*
* Convert samples to bytes, encoding them as 8-bit LPCM values.
*/
func samplesToBytesLPCM8(samples []float64) ([]byte, error) {
numSamples := len(samples)
data := make([]byte, numSamples)
scale := float64(math.MaxInt8)
/*
* Iterate over the samples and encode them as 8-bit LPCM values.
*/
for i, sample := range samples {
/*
* Make sure that limits are not exceeded.
*/
if sample < -1.0 {
sample = -1.0
} else if sample > 1.0 {
sample = 1.0
}
temp := int16(scale * sample)
res := temp - math.MinInt8
/*
* Make sure that limits are not exceeded.
*/
if res < 0 {
data[i] = 0
} else if res > math.MaxUint8 {
data[i] = math.MaxUint8
} else {
data[i] = byte(res)
}
}
return data, nil
}
/*
* Convert bytes, encoded as 8-bit LPCM values, to samples.
*/
func bytesToSamplesLPCM8(data []byte) ([]float64, error) {
numSamples := len(data)
samples := make([]float64, numSamples)
scale := 1.0 / float64(math.MaxInt8)
/*
* Iterate over the samples and decode the 8-bit LPCM values.
*/
for i, byt := range data {
temp := int16(byt) + math.MinInt8
res := scale * float64(temp)
/*
* Make sure that limits are not exceeded.
*/
if res < -1.0 {
samples[i] = -1.0
} else if res > 1.0 {
samples[i] = 1.0
} else {
samples[i] = res
}
}
return samples, nil
}
/*
* Convert samples to bytes, encoding them as 16-bit LPCM values.
*/
func samplesToBytesLPCM16(samples []float64) ([]byte, error) {
numSamples := len(samples)
samplesInt := make([]int16, numSamples)
const delta = math.MaxInt16 - math.MinInt16
scale := 0.5 * float64(delta)
/*
* Iterate over the samples and convert them into integer representation.
*/
for i, sample := range samples {
/*
* Make sure that limits are not exceeded.
*/
if sample < -1.0 {
sample = -1.0
} else if sample > 1.0 {
sample = 1.0
}
tmp := int32(scale * sample)
/*
* Make sure that limits are not exceeded.
*/
if tmp > math.MaxInt16 {
tmp = math.MaxInt16
} else if tmp < math.MinInt16 {
tmp = math.MinInt16
}
samplesInt[i] = int16(tmp)
}
buf := createBuffer()
err := binary.Write(buf, binary.LittleEndian, samplesInt)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to convert samples: %s", msg)
} else {
data := buf.Bytes()
return data, nil
}
}
/*
* Convert bytes, encoded as 16-bit LPCM values, to samples.
*/
func bytesToSamplesLPCM16(data []byte) ([]float64, error) {
numBytes := len(data)
numBytes64 := uint64(numBytes)
numSamples := numBytes64 >> 1
samplesInt := make([]int16, numSamples)
reader := bytes.NewReader(data)
err := binary.Read(reader, binary.LittleEndian, samplesInt)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to decode LPCM16 data: %s", msg)
} else {
samplesFloat := make([]float64, numSamples)
scaling := 2.0 / (math.MaxInt16 - math.MinInt16)
/*
* Convert samples to floating-point representation.
*/
for i, sample := range samplesInt {
samplesFloat[i] = scaling * float64(sample)
}
return samplesFloat, nil
}
}
/*
* Convert samples to bytes, encoding them as 24-bit LPCM values.
*/
func samplesToBytesLPCM24(samples []float64) ([]byte, error) {
const delta = MAX_INT24 - MIN_INT24
scale := 0.5 * float64(delta)
buf := createBuffer()
/*
* Iterate over the samples and convert them into integer representation.
*/
for _, sample := range samples {
/*
* Make sure that limits are not exceeded.
*/
if sample < -1.0 {
sample = -1.0
} else if sample > 1.0 {
sample = 1.0
}
tmp := int32(scale * sample)
/*
* Make sure that limits are not exceeded.
*/
if tmp > MAX_INT24 {
tmp = MAX_INT24
} else if tmp < MIN_INT24 {
tmp = MIN_INT24
}
sampleUint := uint32(tmp)
/*
* Write each byte to the buffer.
*/
for j := 0; j < SIZE_INT24; j++ {
shift := BITS_PER_BYTE * uint32(j)
byt := byte((sampleUint >> shift) & 0xff)
buf.WriteByte(byt)
}
}
data := buf.Bytes()
return data, nil
}
/*
* Convert bytes, encoded as 24-bit LPCM values, to samples.
*/
func bytesToSamplesLPCM24(data []byte) ([]float64, error) {
numBytes := len(data)
numBytes64 := uint64(numBytes)
numSamples := numBytes64 / SIZE_INT24
samplesFloat := make([]float64, numSamples)
scaling := 2.0 / (MAX_INT24 - MIN_INT24)
reader := bytes.NewReader(data)
buf := make([]byte, SIZE_INT24)
words := make([]uint32, SIZE_INT24)
/*
* Read samples from input stream.
*/
for idx := range samplesFloat {
reader.Read(buf)
/*
* Turn the single bytes from the buffer into machine words.
*/
for i, byt := range buf {
words[i] = uint32(byt)
}
sampleWord := uint32(0)
/*
* Combine the extracted words into a single machine word.
*/
for i, word := range words {
shift := BITS_PER_BYTE * uint32(i)
sampleWord |= word << shift
}
sampleInt := int32(sampleWord)
signBit := (sampleWord & SIGN_BIT_INT24) != 0
/*
* Handle negative values in two's complement representation.
*/
if signBit {
offset := sampleInt & MAX_INT24
sampleInt = MIN_INT24 + offset
}
samplesFloat[idx] = scaling * float64(sampleInt)
}
return samplesFloat, nil
}
/*
* Convert samples to bytes, encoding them as 32-bit LPCM values.
*/
func samplesToBytesLPCM32(samples []float64) ([]byte, error) {
numSamples := len(samples)
samplesInt := make([]int32, numSamples)
const delta = math.MaxInt32 - math.MinInt32
scale := 0.5 * float64(delta)
/*
* Iterate over the samples and convert them into integer representation.
*/
for i, sample := range samples {
/*
* Make sure that limits are not exceeded.
*/
if sample < -1.0 {
sample = -1.0
} else if sample > 1.0 {
sample = 1.0
}
tmp := int64(scale * sample)
/*
* Make sure that limits are not exceeded.
*/
if tmp > math.MaxInt32 {
tmp = math.MaxInt32
} else if tmp < math.MinInt32 {
tmp = math.MinInt32
}
samplesInt[i] = int32(tmp)
}
buf := createBuffer()
err := binary.Write(buf, binary.LittleEndian, samplesInt)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to convert samples: %s", msg)
} else {
data := buf.Bytes()
return data, nil
}
}
/*
* Convert bytes, encoded as 32-bit LPCM values, to samples.
*/
func bytesToSamplesLPCM32(data []byte) ([]float64, error) {
numBytes := len(data)
numBytes64 := uint64(numBytes)
numSamples := numBytes64 >> 2
samplesInt := make([]int32, numSamples)
reader := bytes.NewReader(data)
err := binary.Read(reader, binary.LittleEndian, samplesInt)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to decode LPCM32 data: %s", msg)
} else {
samplesFloat := make([]float64, numSamples)
scaling := 2.0 / (math.MaxInt32 - math.MinInt32)
/*
* Convert samples to floating-point representation.
*/
for i, sample := range samplesInt {
samplesFloat[i] = scaling * float64(sample)
}
return samplesFloat, nil
}
}
/*
* Convert samples to bytes, encoding them as 32-bit IEEE floating-point values.
*/
func samplesToBytesIEEE32(samples []float64) ([]byte, error) {
numSamples := len(samples)
samples32 := make([]float32, numSamples)
/*
* Iterate over the samples and convert them into integer representation.
*/
for i, sample := range samples {
/*
* Make sure that limits are not exceeded.
*/
if sample < -1.0 {
sample = -1.0
} else if sample > 1.0 {
sample = 1.0
}
samples32[i] = float32(sample)
}
buf := createBuffer()
err := binary.Write(buf, binary.LittleEndian, samples32)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to convert samples: %s", msg)
} else {
data := buf.Bytes()
return data, nil
}
}
/*
* Convert bytes, encoded as 32-bit IEEE floating-point values, to samples.
*/
func bytesToSamplesIEEE32(data []byte) ([]float64, error) {
numBytes := len(data)
numBytes64 := uint64(numBytes)
numSamples := numBytes64 >> 2
samplesFloat32 := make([]float32, numSamples)
reader := bytes.NewReader(data)
err := binary.Read(reader, binary.LittleEndian, samplesFloat32)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to decode 32-bit IEEE floating-point data: %s", msg)
} else {
samplesFloat := make([]float64, numSamples)
/*
* Convert samples to 64-bit floating-point representation.
*/
for i, sample := range samplesFloat32 {
samplesFloat[i] = float64(sample)
}
return samplesFloat, nil
}
}
/*
* Convert samples to bytes, encoding them as 64-bit IEEE floating-point values.
*/
func samplesToBytesIEEE64(samples []float64) ([]byte, error) {
buf := createBuffer()
err := binary.Write(buf, binary.LittleEndian, samples)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to convert samples: %s", msg)
} else {
data := buf.Bytes()
return data, nil
}
}
/*
* Convert bytes, encoded as 64-bit IEEE floating-point values, to samples.
*/
func bytesToSamplesIEEE64(data []byte) ([]float64, error) {
numBytes := len(data)
numBytes64 := uint64(numBytes)
numSamples := numBytes64 >> 3
samplesFloat64 := make([]float64, numSamples)
reader := bytes.NewReader(data)
err := binary.Read(reader, binary.LittleEndian, samplesFloat64)
/*
* Check if conversion was successful.
*/
if err != nil {
msg := err.Error()
return nil, fmt.Errorf("Failed to decode 64-bit IEEE floating-point data: %s", msg)
} else {
return samplesFloat64, nil
}
}
/*
* Convert samples to bytes, given a sample format and bit depth.
*/
func samplesToBytes(samples []float64, sampleFormat uint16, bitDepth uint16) ([]byte, error) {
/*
* Decide on the sample format.
*/
switch sampleFormat {
case AUDIO_PCM:
/*
* Decide on the bit depth.
*/
switch bitDepth {
case 8:
res, err := samplesToBytesLPCM8(samples)
return res, err
case 16:
res, err := samplesToBytesLPCM16(samples)
return res, err
case 24:
res, err := samplesToBytesLPCM24(samples)
return res, err
case 32:
res, err := samplesToBytesLPCM32(samples)
return res, err
default:
return nil, fmt.Errorf("Unsupported bit depth for audio in LPCM format: %d", bitDepth)
}
case AUDIO_IEEE_FLOAT:
/*
* Decide on the bit depth.
*/
switch bitDepth {
case 32:
res, err := samplesToBytesIEEE32(samples)
return res, err
case 64:
res, err := samplesToBytesIEEE64(samples)
return res, err
default:
return nil, fmt.Errorf("Unsupported bit depth for audio in IEEE floating-point format: %d", bitDepth)
}
default:
return nil, fmt.Errorf("Unknown sample format: %#04x", sampleFormat)
}
}
/*
* Convert bytes to samples, given a sample format and bit depth.
*/
func bytesToSamples(data []byte, sampleFormat uint16, bitDepth uint16) ([]float64, error) {
/*
* Decide on the sample format.
*/
switch sampleFormat {
case AUDIO_PCM:
/*
* Decide on the bit depth.
*/
switch bitDepth {
case 8:
res, err := bytesToSamplesLPCM8(data)
return res, err
case 16:
res, err := bytesToSamplesLPCM16(data)
return res, err
case 24:
res, err := bytesToSamplesLPCM24(data)
return res, err
case 32:
res, err := bytesToSamplesLPCM32(data)
return res, err
default:
return nil, fmt.Errorf("Unsupported bit depth for audio in LPCM format: %d", bitDepth)
}
case AUDIO_IEEE_FLOAT:
/*
* Decide on the bit depth.
*/
switch bitDepth {
case 32:
res, err := bytesToSamplesIEEE32(data)
return res, err
case 64:
res, err := bytesToSamplesIEEE64(data)
return res, err
default:
return nil, fmt.Errorf("Unsupported bit depth for audio in IEEE floating-point format: %d", bitDepth)
}
default:
return nil, fmt.Errorf("Unknown sample format: %#04x", sampleFormat)
}
}
/*
* Returns the sample depth of this wave file in bits.
*/
func (this *fileStruct) BitDepth() uint16 {
return this.bitDepth
}
/*
* Returns the contents of this wave file as a byte slice.
*/
func (this *fileStruct) Bytes() ([]byte, error) {
channelCount := len(this.channels)
channelCount16 := uint16(channelCount)
channelCount32 := uint32(channelCount)
bitDepth := this.bitDepth
sampleFormat := this.sampleFormat
sampleRate := this.sampleRate
sampleSize32 := uint32(bitDepth / BITS_PER_BYTE)
sampleSize64 := uint64(sampleSize32)
blockAlign := sampleSize32 * channelCount32
blockAlign16 := uint16(blockAlign)
byteRate := sampleRate * blockAlign
samples := channelsToSamples(this.channels)
numSamples := len(samples)
data, err := samplesToBytes(samples, sampleFormat, bitDepth)
/*
* Check if conversion was successful.
*/
if err != nil {
return nil, err
} else {
idRIFF := uint32(ID_RIFF)
numSamples32 := uint32(numSamples)
numSamples64 := uint64(numSamples)
dataBytes32 := sampleSize32 * numSamples32
dataBytes64 := sampleSize64 * numSamples64
riffSize64 := dataBytes64 + (MIN_TOTAL_HEADER_SIZE - MIN_CHUNK_HEADER_SIZE)
riffSize32 := uint32(riffSize64)
requiresRF64 := riffSize64 > math.MaxUint32
/*
* If we write an RF64 file, replace RIFF chunk ID with 'RF64' and set 32-bit size to math.MaxUint32 (0xffffffff).
*/
if requiresRF64 {
idRIFF = uint32(ID_RIFF64)
riffSize32 = math.MaxUint32
}
/*
* Create RIFF header.
*/
hdrRiff := riffHeader{
ChunkID: idRIFF,
ChunkSize: riffSize32,
Format: FORMAT_WAVE,
}
/*
* Create data size header.
*/
hdrDataSize := dataSizeHeader{
ChunkID: ID_DATASIZE,
ChunkSize: MIN_DATASIZE_CHUNK_SIZE,
SizeRIFF: riffSize64,
SizeData: dataBytes64,
SampleCount: numSamples64,
TableLength: 0,
}
/*
* Create format header.
*/
hdrFormat := formatHeader{
ChunkID: ID_FORMAT,
ChunkSize: MIN_CHUNK_SIZE_FORMAT,
AudioFormat: sampleFormat,
ChannelCount: channelCount16,
SampleRate: sampleRate,
ByteRate: byteRate,
BlockAlign: blockAlign16,
BitDepth: bitDepth,
}
/*
* Create data header.
*/
hdrData := dataHeader{
ChunkID: ID_DATA,
ChunkSize: dataBytes32,
}
buf := createBuffer()
binary.Write(buf, binary.LittleEndian, hdrRiff)
/*
* If we write an RF64 file, write mandatory data size chunk.
*/
if requiresRF64 {
binary.Write(buf, binary.LittleEndian, hdrDataSize)
}
binary.Write(buf, binary.LittleEndian, hdrFormat)
binary.Write(buf, binary.LittleEndian, hdrData)
buf.Write(data)
content := buf.Bytes()
return content, nil
}
}
/*
* Returns a reference to the requested channel.
*/
func (this *fileStruct) Channel(id uint16) (Channel, error) {
channelCount := this.ChannelCount()
/*
* Check whether the requested channel is available in this wave file.
*/
if id >= channelCount {
return nil, fmt.Errorf("No channel with id = %d in this wave file with channel count %d.", id, channelCount)
} else {
c := this.channels[id]
return c, nil
}
}
/*
* Returns the number of channels available in this wave file.
*/
func (this *fileStruct) ChannelCount() uint16 {
n := len(this.channels)
n16 := uint16(n)
return n16
}
/*
* Returns the format code of the sample format of this wave file.
*/
func (this *fileStruct) SampleFormat() uint16 {
return this.sampleFormat
}
/*
* Returns the sample rate of this wave file in Hertz.
*/
func (this *fileStruct) SampleRate() uint32 {
return this.sampleRate
}
/*
* Creates an empty channel.
*/
func createChannel() Channel {
channel := channelStruct{}
return &channel
}
/*