-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
97 lines (90 loc) · 2.3 KB
/
reader.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
package wave
import (
"io"
"github.com/bake/wave/riff"
"github.com/pkg/errors"
)
// Reader reads samples from a WAVE file.
type Reader struct {
rr *riff.Reader
Format Format
}
// NewReader reads the initial chunks from a WAVE file and returns a new reader.
func NewReader(r io.Reader) (*Reader, error) {
rr, t, err := riff.NewReader(r)
if err != nil {
return nil, errors.Wrap(err, "could not create new riff reader")
}
if t != "WAVE" {
return nil, errors.Errorf("unexpected riff type %s", t)
}
if !rr.Next() {
if rr.Error() == nil {
return nil, errors.Wrap(io.EOF, "unecpected eof before fomat chunk")
}
return nil, errors.Wrap(rr.Error(), "could not read format chunk")
}
id, _, data := rr.Chunk()
if id != "fmt " {
return nil, errors.Errorf("unexpected chunk id %s", id)
}
format, err := decodeFormat(data)
if err != nil {
return nil, errors.Wrap(err, "could not decode format chunk")
}
return &Reader{rr, format}, nil
}
// Sample returns the next sample from the wave file. Chunks that don't contain
// samples are skipped.
func (wavr *Reader) Sample() (int, error) {
id, size, data := wavr.rr.Chunk()
if id != "data" {
body := make([]byte, size)
if _, err := data.Read(body); err != nil && err != io.EOF {
return 0, errors.Wrapf(err, "could not skip %s chunk", id)
}
wavr.rr.Next()
return wavr.Sample()
}
s, err := wavr.sample(data)
if err == io.EOF {
if !wavr.rr.Next() {
return 0, io.EOF
}
return wavr.Sample()
}
return s, err
}
// Samples reads the whole file and returns all samples.
func (wavr *Reader) Samples() ([]int, error) {
var samples []int
for {
s, err := wavr.Sample()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
samples = append(samples, s)
}
return samples, nil
}
func (wavr *Reader) sample(r io.Reader) (int, error) {
s := make([]byte, wavr.Format.BitsPerSample/8)
if _, err := r.Read(s); err != nil {
return 0, err
}
switch wavr.Format.BitsPerSample {
case 8:
return int(uint8(s[0])), nil
case 16:
return int(int16(s[0]) | int16(s[1])<<8), nil
case 24:
return int(int32(s[0]) | int32(s[1])<<8 | int32(s[2])<<16), nil
case 32:
return int(int32(s[0]) | int32(s[1])<<8 | int32(s[2])<<16 | int32(s[3])<<24), nil
default:
return 0, errors.Errorf("unpexpected bps: %d", wavr.Format.BitsPerSample)
}
}