-
Notifications
You must be signed in to change notification settings - Fork 13
/
ears.go
116 lines (92 loc) · 1.71 KB
/
ears.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
package alexa
import (
"bytes"
"encoding/binary"
"os"
"os/signal"
"time"
"github.com/evanphx/alexa/portaudio"
)
const DefaultQuietTime = time.Second
func ListenIntoBuffer(opts ListenOpts) (*bytes.Buffer, error) {
portaudio.Initialize()
defer portaudio.Terminate()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
defer signal.Reset(os.Interrupt, os.Kill)
in := make([]int16, 8196)
stream, err := portaudio.OpenDefaultStream(1, 0, 16000, len(in), in)
if err != nil {
return nil, err
}
defer stream.Close()
err = stream.Start()
if err != nil {
return nil, err
}
var (
buf bytes.Buffer
heardSomething bool
quiet bool
quietTime = opts.QuietDuration
quietStart time.Time
lastFlux float64
)
vad := NewVAD(len(in))
if quietTime == 0 {
quietTime = DefaultQuietTime
}
if opts.State != nil {
opts.State(Waiting)
}
reader:
for {
err = stream.Read()
if err != nil {
return nil, err
}
err = binary.Write(&buf, binary.LittleEndian, in)
if err != nil {
return nil, err
}
flux := vad.Flux(in)
if lastFlux == 0 {
lastFlux = flux
continue
}
if heardSomething {
if flux*1.75 <= lastFlux {
if !quiet {
quietStart = time.Now()
} else {
diff := time.Since(quietStart)
if diff > quietTime {
break reader
}
}
quiet = true
} else {
quiet = false
lastFlux = flux
}
} else {
if flux >= lastFlux*1.75 {
heardSomething = true
if opts.State != nil {
opts.State(Listening)
}
}
lastFlux = flux
}
select {
case <-sig:
break reader
default:
}
}
err = stream.Stop()
if err != nil {
return nil, err
}
return &buf, nil
}