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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
package audio

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"path/filepath"

)

/*
-----RIFF-----
RIFF			4	标头字母
CHUNK_SIZE		4	整个RIFF文件的长度(不包含RIFF和CHUNK_SIZE这两个字段的长度)
FORMAT			4	格式,WAVE代表是wav文件,WAVE格式要求带有标头为fmt和data的子chunk
-----FMT -----
SUB_CHUNK_ID	4	子chunk的标头字母,此处为"fmt "(注意,fmt后面是带一个空格的),其相当于wav的属性字段
SUB_CHUNK_SIZE	4	此subchunk的长度(不包含SUB_CHUNK_ID和SUB_CHUNK_SIZE两个字段的长度)
AUDIO_FORMAT	2	音频格式,pcm为1
NUM_CHANNELS	2	声道数量,理论上可以n声道,一般我们用单声道mono,或者双声道stereo(双声道也叫立体声)
SAMPLE_RATE		4	采样率,每秒采样多少次,通常都有固定的采样选择(8000, 11025,12000,16000,22050,24000,32000,44100,48000)
BYTE_RATE		4	码率,即每秒播放多少byte数据,计算公式=SAMPLE_RATE*NUM_CHANNELS*BITS_PER_SAMPLE/8(不明白为何需要这个字段)
BLOCK_ALIGN		2	块对其,其值=BITS_PER_SAMPLE*NUM_CHANNELS/8
BITS_PER_SAMPLE 2	每个采样多少bit,通常为8,16,32(为8时候代表的是uint8,16代表的是int16,32代表float32)
-----DATA-----
SUB_CHUNK_ID	4	子chunk的标头字母,此处为"data"
SUB_CHUNK_SIZE	4	此subchunk的长度(不包含SUB_CHUNK_ID和SUB_CHUNK_SIZE两个字段的长度)
DATA				pcm的数据
-------------
*/

//MaxChannelNum 最大声道数量(此处只允许2)
const MaxChannelNum = 2

const (
	LeftChannel = 0
	RightChannel =1
)

//tag tag定义
type tag [4]byte

//一些变量
var (
	tagRIFF = tag{'R', 'I', 'F', 'F'} // "RIFF"
	tagWAVE = tag{'W', 'A', 'V', 'E'} // "WAVE"
	tagFmt  = tag{'f', 'm', 't', ' '} // "fmt "
	tagData = tag{'d', 'a', 't', 'a'} // "data"
)

//WavHeaderType wav子部头结构
type WavHeaderType struct {
	ID   tag
	Size uint32
}

//String 打印
func (wavHeader *WavHeaderType) String() string {
	return fmt.Sprintf("ID=%s,Size=%d", string(wavHeader.ID[:]), wavHeader.Size)
}

//头部size
var (
	sizeHeader = binary.Size(WavHeaderType{})
)

//chunkLoc ...
type chunkLoc struct {
	pos  int64
	size int64
}

//RiffType ...
type RiffType struct {
	WavHeaderType
	Fmt tag
}

//String ...
func (riff *RiffType) String() string {
	return fmt.Sprintf("ID=%s,Size=%d,Fmt=%s", string(riff.ID[:]), riff.Size, string(riff.Fmt[:]))
}

//WavFmtType wav格式结构(头部)
type WavFmtType struct {
	WavHeaderType
	AudioFormat   uint16
	Channels      uint16
	SampleRate    uint32
	BytesPerSec   uint32
	BytesPerBlock uint16
	BitsPerSample uint16
}

//String ...
func (wavFmt *WavFmtType) String() string {
	return fmt.Sprintf(
		"ID=%s,Size=%d,AudioFormat=%d,Channels=%d,SampleRate=%d,BytesPerSec=%d,BytesPerBlock=%d,BitsPerSample=%d",
		string(wavFmt.ID[:]), wavFmt.Size, wavFmt.AudioFormat, wavFmt.Channels, wavFmt.SampleRate,
		wavFmt.BytesPerSec, wavFmt.BytesPerBlock, wavFmt.BitsPerSample)
}

//SampleType 采样结构
type SampleType struct {
	val8s  [MaxChannelNum]uint8
	val16s [MaxChannelNum]int16
	val32s [MaxChannelNum]float32
}

//WavDataType wav整体结构(头部+采样数据结构)
type WavDataType struct {
	WavHeaderType
	Sample []SampleType
}

//String ...
func (wavData *WavDataType) String() string {
	blockNum := len(wavData.Sample)
	return fmt.Sprintf("ID=%s,Size=%d,BlockNum=%d", string(wavData.ID[:]), wavData.Size, blockNum)
}

//WavInfoType wav操作实例
type WavInfoType struct {
	Riff RiffType
	Fmt  WavFmtType
	Data WavDataType

	//create info
	createMs int64
}

//String ...
func (wavInfo *WavInfoType) String() string {
	f := &wavInfo.Fmt
	blockNum := len(wavInfo.Data.Sample)
	return fmt.Sprintf("SampleRate=%d,BitsPerSample=%d,Channels=%d,BlockNum=%d",
		f.SampleRate, f.BitsPerSample, f.Channels, blockNum)

}

//SetCreateTs ...
func (wavInfo *WavInfoType) SetCreateTs(timestampMs int64) {
	wavInfo.createMs = timestampMs
}

//CopyFormat 复制头部结构
func (wavInfo *WavInfoType) CopyFormat(w *WavInfoType) (err error) {
	wavInfo.Riff.ID = w.Riff.ID
	wavInfo.Riff.Size = w.Riff.Size
	wavInfo.Riff.Fmt = w.Riff.Fmt
	wavInfo.Fmt.ID = w.Fmt.ID
	wavInfo.Fmt.Size = w.Fmt.Size
	wavInfo.Fmt.AudioFormat = w.Fmt.AudioFormat
	wavInfo.Fmt.Channels = w.Fmt.Channels
	wavInfo.Fmt.SampleRate = w.Fmt.SampleRate
	wavInfo.Fmt.BytesPerSec = w.Fmt.BytesPerSec
	wavInfo.Fmt.BytesPerBlock = w.Fmt.BytesPerBlock
	wavInfo.Fmt.BitsPerSample = w.Fmt.BitsPerSample
	wavInfo.Data.ID = w.Data.ID
	wavInfo.Data.Size = w.Data.Size
	return
}

//ParseFromFile 从文件中导入
func (wavInfo *WavInfoType) ParseFromFile(absFile string) (err error) {
	absFile, err = filepath.Abs(absFile) //#nosec
	if err != nil {
		return err
	}
	fileHandler, err := os.Open(absFile) //#nosec
	if err != nil {
		return err
	}
	defer fileHandler.Close()

	_, err = fileHandler.Seek(0, os.SEEK_SET)
	if err != nil {
		return err
	}

	var pos int64
	var ch WavHeaderType

	//-----------------------------------------------------
	// RIFF header
	err = binary.Read(fileHandler, binary.LittleEndian, &wavInfo.Riff)
	if err != nil {
		return err
	}
	pos += int64(sizeHeader) + int64(len(tagWAVE))
	if wavInfo.Riff.ID != tagRIFF {
		return errors.New("File Format Not Riff")
	}
	if wavInfo.Riff.Fmt != tagWAVE {
		return errors.New("File Format Not Wave")
	}
	fileSize := int64(sizeHeader) + int64(wavInfo.Riff.Size)
	_ = fileSize

	//r := &wavInfo.Riff

	//-----------------------------------------------------
	// read all chunks

	var chunks = make(map[tag]*chunkLoc)

	for {
		err = binary.Read(fileHandler, binary.LittleEndian, &ch)
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		pos += int64(sizeHeader)

		loc := chunkLoc{
			pos:  pos,
			size: int64(ch.Size),
		}

		_, err = fileHandler.Seek(loc.size, os.SEEK_CUR)
		if err != nil {
			return err
		}
		pos += loc.size // chunk data

		chunks[ch.ID] = &loc
	}

	// check fileHandler size
	if pos != fileSize {
		return errors.New("pos != fileSize")
	}

	//-----------------------------------------------------
	// chunk fmt_
	loc, ok := chunks[tagFmt]
	if !ok {
		return errors.New("wav: has not chunk \"fmt \"")
	}
	_, err = fileHandler.Seek(loc.pos-int64(sizeHeader), os.SEEK_SET)
	if err != nil {
		return err
	}
	err = binary.Read(fileHandler, binary.LittleEndian, &wavInfo.Fmt)
	if err != nil {
		return err
	}

	//-----------------------------------------------------
	// chunk data
	loc, ok = chunks[tagData]
	if !ok {
		return errors.New("wav: has not chunk \"data\"")
	}
	_, err = fileHandler.Seek(loc.pos, os.SEEK_SET)
	if err != nil {
		return err
	}

	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	blockSize := channel * bytePerSample

	wavInfo.Data.ID = tagData
	wavInfo.Data.Size = uint32(loc.size)

	blockNum := wavInfo.Data.Size / uint32(blockSize)
	wavInfo.Data.Sample = make([]SampleType, blockNum)

	_, err = fileHandler.Seek(loc.pos, os.SEEK_SET)
	if err != nil {
		return err
	}
	blockIdx := 0
	for i := 0; i < int(wavInfo.Data.Size); i += int(blockSize) {
		sample := &wavInfo.Data.Sample[blockIdx]
		blockIdx++
		for c := 0; c < int(channel); c++ {
			switch bytePerSample {
			case 1:
				var val uint8
				err = binary.Read(fileHandler, binary.LittleEndian, &val)
				//sample.val8s = append(sample.val8s,val)
				sample.val8s[c] = val
			case 2:
				var val int16
				err = binary.Read(fileHandler, binary.LittleEndian, &val)
				//sample.val16s = append(sample.val16s,val)
				sample.val16s[c] = val
				//fmt.Printf("pos=%d,val=%d\n",i,sample.val16s)
			case 4:
				var val float32
				err = binary.Read(fileHandler, binary.LittleEndian, &val)
				//sample.val32s = append(sample.val32s,val)
				sample.val32s[c] = val

			}
			if err != nil {
				return err
			}
		}
		//wavInfo.Data.Sample = append(wavInfo.Data.Sample,sample)
	}

	//for i:=0;i<len(wavInfo.Data.Sample);i++{
	//	sample := &wavInfo.Data.Sample[i]
	//	fmt.Printf("idx=%d,left=%d,right=%d\n",i,sample.val16s[0],sample.val16s[1])
	//}

	for id, chunk := range chunks {
		if id != tagData && id != tagFmt {
			//util.MainLogger.Error(fmt.Sprintf("unkonw chunk=%s,size=%d\n", string(id[:]), chunk.size))
			fmt.Printf("unkonw chunk=%s,size=%d\n", string(id[:]), chunk.size)
		}
	}
	return
}

//ParseFromBuffer 从buffer中导入
func (wavInfo *WavInfoType) ParseFromBuffer(buffer []byte) (err error) {
	var ch WavHeaderType

	bufferReader := bytes.NewBuffer(buffer)
	//-----------------------------------------------------
	// RIFF header
	err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Riff)
	if err != nil {
		return err
	}

	//pos := int64(sizeHeader) + int64(len(tagWAVE))
	if wavInfo.Riff.ID != tagRIFF {
		return errors.New("File Format Not Riff")
	}
	if wavInfo.Riff.Fmt != tagWAVE {
		return errors.New("File Format Not Wave")
	}
	fileSize := int64(sizeHeader) + int64(wavInfo.Riff.Size)
	_ = fileSize

	//r := &wavInfo.Riff

	//-----------------------------------------------------
	// read all chunks
	for {
		err = binary.Read(bufferReader, binary.LittleEndian, &ch)
		if err != nil {
			if err == io.EOF {
				//文件读取结束
				err = nil
				return
			}
			return err
		}

		//fmt格式的chunk
		if ch.ID == tagFmt {
			wavInfo.Fmt.WavHeaderType = ch
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.AudioFormat)
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.Channels)
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.SampleRate)
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.BytesPerSec)
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.BytesPerBlock)
			err = binary.Read(bufferReader, binary.LittleEndian, &wavInfo.Fmt.BitsPerSample)
			if err != nil {
				return err
			}
			continue
		}

		//data格式的chunk
		if ch.ID == tagData {
			channel := wavInfo.Fmt.Channels
			bytePerSample := wavInfo.Fmt.BitsPerSample / 8
			blockSize := channel * bytePerSample

			wavInfo.Data.ID = tagData
			wavInfo.Data.Size = ch.Size

			blockNum := wavInfo.Data.Size / uint32(blockSize)
			wavInfo.Data.Sample = make([]SampleType, blockNum)

			blockIdx := 0
			for i := 0; i < int(wavInfo.Data.Size); i += int(blockSize) {
				sample := &wavInfo.Data.Sample[blockIdx]
				blockIdx++
				for c := 0; c < int(channel); c++ {
					switch bytePerSample {
					case 1:
						var val uint8
						err = binary.Read(bufferReader, binary.LittleEndian, &val)
						//sample.val8s = append(sample.val8s,val)
						sample.val8s[c] = val
					case 2:
						var val int16
						err = binary.Read(bufferReader, binary.LittleEndian, &val)
						//sample.val16s = append(sample.val16s,val)
						sample.val16s[c] = val
						//fmt.Printf("pos=%d,val=%d\n",i,sample.val16s)
					case 4:
						var val float32
						err = binary.Read(bufferReader, binary.LittleEndian, &val)
						//sample.val32s = append(sample.val32s,val)
						sample.val32s[c] = val

					}
					if err != nil {
						return err
					}
				}
				//wavInfo.Data.Sample = append(wavInfo.Data.Sample,sample)
			}
			continue
		}

		//其他格式的chunk
		byteData := make([]byte, ch.Size)
		err = binary.Read(bufferReader, binary.LittleEndian, byteData)
	}
	return
}

//SaveToFile 保存到文件中
func (wavInfo *WavInfoType) SaveToFile(absFile string) (err error) {
	file, err := os.Create(absFile)
	if err != nil {
		return
	}
	defer file.Close()
	_, err = file.Seek(0, os.SEEK_SET)
	if err != nil {
		return
	}

	//calc size
	wavInfo.Data.Size = (uint32(wavInfo.Fmt.Channels) * uint32(wavInfo.Fmt.BitsPerSample) / 8) *
		uint32(len(wavInfo.Data.Sample))
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	wavInfo.Riff.Size = uint32(len(wavInfo.Riff.Fmt)) +
		uint32(sizeHeader) +
		wavInfo.Fmt.Size +
		uint32(sizeHeader) +
		wavInfo.Data.Size

	//----------------------------------------
	// RIFF header
	err = binary.Write(file, binary.LittleEndian, wavInfo.Riff)
	if err != nil {
		return err
	}

	//----------------------------------------
	// chunk fmt_
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	err = binary.Write(file, binary.LittleEndian, wavInfo.Fmt)
	if err != nil {
		return err
	}

	//----------------------------------------
	// chunk data
	ch := WavHeaderType{
		ID:   tagData,
		Size: wavInfo.Data.Size,
	}
	err = binary.Write(file, binary.LittleEndian, ch)
	if err != nil {
		return err
	}

	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		sample := &wavInfo.Data.Sample[i]
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(file, binary.LittleEndian, sample.val8s[c])
				if err != nil {
					return
				}

			}
		case 2:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(file, binary.LittleEndian, sample.val16s[c])
				if err != nil {
					return
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(file, binary.LittleEndian, sample.val32s[c])
				if err != nil {
					return
				}
			}
		}
	}
	return
}

//SaveToBuffer 保存到buffer中
func (wavInfo *WavInfoType) SaveToBuffer() (buffer []byte, err error) {

	//var bufferWriter   bytes.Buffer
	buffer = make([]byte, 0)
	bufferWriter := bytes.NewBuffer(buffer)

	//calc size
	wavInfo.Data.Size = (uint32(wavInfo.Fmt.Channels) * uint32(wavInfo.Fmt.BitsPerSample) / 8) *
		uint32(len(wavInfo.Data.Sample))
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	wavInfo.Riff.Size = uint32(len(wavInfo.Riff.Fmt)) +
		uint32(sizeHeader) +
		wavInfo.Fmt.Size +
		uint32(sizeHeader) +
		wavInfo.Data.Size

	//----------------------------------------
	// RIFF header
	err = binary.Write(bufferWriter, binary.LittleEndian, wavInfo.Riff)
	if err != nil {
		return
	}

	//----------------------------------------
	// chunk fmt_
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	err = binary.Write(bufferWriter, binary.LittleEndian, wavInfo.Fmt)
	if err != nil {
		return
	}

	//----------------------------------------
	// chunk data
	ch := WavHeaderType{
		ID:   tagData,
		Size: wavInfo.Data.Size,
	}
	err = binary.Write(bufferWriter, binary.LittleEndian, ch)
	if err != nil {
		return
	}

	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		sample := &wavInfo.Data.Sample[i]
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(bufferWriter, binary.LittleEndian, sample.val8s[c])
				if err != nil {
					return
				}
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(bufferWriter, binary.LittleEndian, sample.val16s[c])
				if err != nil {
					return
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {
				err = binary.Write(bufferWriter, binary.LittleEndian, sample.val32s[c])
				if err != nil {
					return
				}
			}
		}
	}
	buffer = bufferWriter.Bytes()
	return
}

//SaveToBuffer 保存到buffer中
func (wavInfo *WavInfoType) SaveToBufferWithChannel(voiceChannel int) (buffer []byte, err error) {

	//var bufferWriter   bytes.Buffer
	buffer = make([]byte, 0)
	bufferWriter := bytes.NewBuffer(buffer)

	//calc size
	channel := wavInfo.Fmt.Channels
	wavInfo.Fmt.Channels = 1
	wavInfo.Data.Size = (uint32(wavInfo.Fmt.Channels) * uint32(wavInfo.Fmt.BitsPerSample) / 8) *
		uint32(len(wavInfo.Data.Sample))
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	wavInfo.Riff.Size = uint32(len(wavInfo.Riff.Fmt)) +
		uint32(sizeHeader) +
		wavInfo.Fmt.Size +
		uint32(sizeHeader) +
		wavInfo.Data.Size

	//----------------------------------------
	// RIFF header
	err = binary.Write(bufferWriter, binary.LittleEndian, wavInfo.Riff)
	if err != nil {
		return
	}

	//----------------------------------------
	// chunk fmt_
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	err = binary.Write(bufferWriter, binary.LittleEndian, wavInfo.Fmt)
	if err != nil {
		return
	}

	//----------------------------------------
	// chunk data
	ch := WavHeaderType{
		ID:   tagData,
		Size: wavInfo.Data.Size,
	}
	err = binary.Write(bufferWriter, binary.LittleEndian, ch)
	if err != nil {
		return
	}


	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		sample := &wavInfo.Data.Sample[i]
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(bufferWriter, binary.LittleEndian, sample.val8s[c])
					if err != nil {
						return
					}
				}
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(bufferWriter, binary.LittleEndian, sample.val16s[c])
					if err != nil {
						return
					}
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(bufferWriter, binary.LittleEndian, sample.val32s[c])
					if err != nil {
						return
					}
				}
			}
		}
	}
	buffer = bufferWriter.Bytes()
	wavInfo.Fmt.Channels = 2
	return
}

//SaveToFile 保存到文件中
func (wavInfo *WavInfoType) SaveToFileWithChannel(absFile string, voiceChannel int) (err error) {
	file, err := os.Create(absFile)
	if err != nil {
		return
	}
	defer file.Close()
	_, err = file.Seek(0, io.SeekStart)
	if err != nil {
		return
	}

	//calc size
	channel := wavInfo.Fmt.Channels
	wavInfo.Fmt.Channels = 1
	wavInfo.Data.Size = (uint32(wavInfo.Fmt.Channels) * uint32(wavInfo.Fmt.BitsPerSample) / 8) *
		uint32(len(wavInfo.Data.Sample))
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	wavInfo.Riff.Size = uint32(len(wavInfo.Riff.Fmt)) +
		uint32(sizeHeader) +
		wavInfo.Fmt.Size +
		uint32(sizeHeader) +
		wavInfo.Data.Size

	//----------------------------------------
	// RIFF header
	err = binary.Write(file, binary.LittleEndian, wavInfo.Riff)
	if err != nil {
		return err
	}

	//----------------------------------------
	// chunk fmt_
	wavInfo.Fmt.Size = uint32(binary.Size(wavInfo.Fmt)) - uint32(sizeHeader)
	err = binary.Write(file, binary.LittleEndian, wavInfo.Fmt)
	if err != nil {
		return err
	}

	//----------------------------------------
	// chunk data
	ch := WavHeaderType{
		ID:   tagData,
		Size: wavInfo.Data.Size,
	}
	err = binary.Write(file, binary.LittleEndian, ch)
	if err != nil {
		return err
	}

	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		sample := &wavInfo.Data.Sample[i]
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(file, binary.LittleEndian, sample.val8s[c])
					if err != nil {
						return
					}
				}
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(file, binary.LittleEndian, sample.val16s[c])
					if err != nil {
						return
					}
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {
				if voiceChannel == c {
					err = binary.Write(file, binary.LittleEndian, sample.val32s[c])
					if err != nil {
						return
					}
				}
			}
		}
	}
	wavInfo.Fmt.Channels = 2
	return
}

//AdjusterVolume 调整音量
func (wavInfo *WavInfoType) AdjusterVolume(rateAsRaw float32) {
	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	const MaxUint8 = math.MaxUint8
	const MinUint8 = 0
	const MaxInt16 = math.MaxInt16
	const MinInt16 = math.MinInt16

	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val8s[c]
				clip := float64(val) * float64(rateAsRaw)
				if clip < MinUint8 {
					clip = MinUint8
				}
				if clip > MaxUint8 {
					clip = MaxUint8
				}
				//wavInfo.Data.Sample[i].val8s[c] = uint8((float32(val) * rateAsRaw))
				wavInfo.Data.Sample[i].val8s[c] = uint8(clip)
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				//val := wavInfo.Data.Sample[i].val16s[c]
				//wavInfo.Data.Sample[i].val16s[c] = int16((float32(val) * rateAsRaw))
				val := wavInfo.Data.Sample[i].val16s[c]
				clip := float64(val) * float64(rateAsRaw)
				if clip < MinInt16 {
					clip = MinInt16
				}
				if clip > MaxInt16 {
					clip = MaxInt16
				}
				wavInfo.Data.Sample[i].val16s[c] = int16(clip)
			}
		case 4:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val32s[c]
				wavInfo.Data.Sample[i].val32s[c] = val * rateAsRaw
			}
		}
	}
}

//Resample 重置采样率
func (wavInfo *WavInfoType) Resample(resampleRate uint32) {
	sampleRate := wavInfo.Fmt.SampleRate
	rate := float64(sampleRate) / float64(resampleRate)
	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	rawLen := len(wavInfo.Data.Sample)

	resampleData := make([]SampleType, 0)

	resampleIdx := 0
	for {
		rawIdx := int(float64(resampleIdx) * rate)
		if rawIdx < rawLen {
			sample := SampleType{}
			for c := 0; c < int(channel); c++ {
				switch bytePerSample {
				case 1:
					val := wavInfo.Data.Sample[rawIdx].val8s[c]
					//sample.val8s = append(sample.val8s,val)
					sample.val8s[c] = val
				case 2:
					val := wavInfo.Data.Sample[rawIdx].val16s[c]
					//sample.val16s = append(sample.val16s,val)
					sample.val16s[c] = val
				case 4:
					val := wavInfo.Data.Sample[rawIdx].val32s[c]
					//sample.val32s = append(sample.val32s,val)
					sample.val32s[c] = val
				}
			}
			resampleData = append(resampleData, sample)
		} else {
			break
		}
		resampleIdx++
	}

	wavInfo.Data.Sample = resampleData
	wavInfo.Fmt.SampleRate = resampleRate

}

//ConvertToFloat32 将采样值转换到 0 到 1 之间
func (wavInfo *WavInfoType) GetFloat32Samples(channel int, bytePerSample int) []float32 {
	//fmt.Println(wavInfo.cha)

	var floatSamples []float32

	var point float32
	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		sample := &wavInfo.Data.Sample[i]
		switch bytePerSample {
		case 1:
			point = float32(sample.val8s[channel]) / (1 << 8)
		case 2:
			point = float32(sample.val16s[channel]) / (1 << 15)
		case 4:
			point = sample.val32s[channel]
		}
		floatSamples = append(floatSamples, point)
	}
	return floatSamples
}

//Trim 切头切尾
func (wavInfo *WavInfoType) Trim(dbPercent float32) {
	channel := wavInfo.Fmt.Channels
	bytePerSample := wavInfo.Fmt.BitsPerSample / 8
	//blockSize := channel*bytePerSample

	const MaxUint8 = math.MaxUint8
	const MinUint8 = 0
	const MaxInt16 = math.MaxInt16
	const MinInt16 = math.MinInt16

	//trim head
	silenceHeadIdx := 0 //头部静音截止位置
	done := false
	for i := 0; i < len(wavInfo.Data.Sample); i++ {
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val8s[c]
				if float32(val) > MaxUint8*dbPercent {
					silenceHeadIdx = i
					done = true
					break
				}
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val16s[c]
				if float32(val) > MaxInt16*dbPercent {
					silenceHeadIdx = i
					done = true
					break
				}
				if float32(val) < MinInt16*dbPercent {
					silenceHeadIdx = i
					done = true
					break
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {

				val := wavInfo.Data.Sample[i].val32s[c]
				if float32(val) > math.MaxFloat32*dbPercent {
					silenceHeadIdx = i
					done = true
					break
				}
				if val < 0 && (-val > math.MaxFloat32*dbPercent) {
					silenceHeadIdx = i
					done = true
					break
				}
			}
		}

		if done {
			break
		}
	}

	//trim tail,截断尾部
	silenceTailIdx := len(wavInfo.Data.Sample) - 1 //尾部静音截止位置
	done = false
	for i := len(wavInfo.Data.Sample) - 1; i >= 0; i-- {
		switch bytePerSample {
		case 1:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val8s[c]
				if float32(val) > MaxUint8*dbPercent {
					silenceTailIdx = i
					done = true
					break
				}
			}
		case 2:
			for c := 0; c < int(channel); c++ {
				val := wavInfo.Data.Sample[i].val16s[c]
				if val >= 0 && float32(val) > float32(MaxInt16*dbPercent) {
					silenceTailIdx = i
					done = true
					break
				}
				if val < 0 && float32(val) < float32(MinInt16*dbPercent) {
					silenceTailIdx = i
					done = true
					break
				}
			}
		case 4:
			for c := 0; c < int(channel); c++ {

				val := wavInfo.Data.Sample[i].val32s[c]
				if float32(val) > math.MaxFloat32*dbPercent {
					silenceTailIdx = i
					done = true
					break
				}
				if val < 0 && (-val > math.MaxFloat32*dbPercent) {
					silenceTailIdx = i
					done = true
					break
				}
			}
		}

		if done {
			break
		}
	}

	wavInfo.Data.Sample = wavInfo.Data.Sample[:silenceTailIdx]
	wavInfo.Data.Sample = wavInfo.Data.Sample[silenceHeadIdx:]
}

func (wavInfo *WavInfoType) TrimFirstWithTime(milliseconds int64) error{
	sampleRate := wavInfo.Fmt.SampleRate
	sizeToTrim :=  int64(sampleRate) * milliseconds / 1000
	if int(sizeToTrim) >= len(wavInfo.Data.Sample) {
		return errors.New("check time err")
	}
	wavInfo.Data.Sample = wavInfo.Data.Sample[sizeToTrim:]
	return nil
}

func (wavInfo *WavInfoType) GetWavTime() int {
	return int(math.Ceil(float64(len(wavInfo.Data.Sample)) / float64(wavInfo.Fmt.SampleRate)))
}

//NewWavInfo 新建一个wav操作实例
func NewWavInfo() *WavInfoType {
	w := &WavInfoType{}
	return w
}