-
Notifications
You must be signed in to change notification settings - Fork 47
/
main.go
168 lines (149 loc) · 4.48 KB
/
main.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
package main
import (
"log"
"os"
"unsafe"
"github.com/jawher/mow.cli"
"github.com/xlab/closer"
"github.com/xlab/pocketsphinx-go/sphinx"
"github.com/xlab/portaudio-go/portaudio"
)
const (
samplesPerChannel = 512
sampleRate = 16000
channels = 1
sampleFormat = portaudio.PaInt16
)
var (
app = cli.App("gortana", "Goratana is a dumb personal assistant to test how CMUSphinx works from Golang.")
hmm = app.StringOpt("hmm", "/usr/local/share/pocketsphinx/model/en-us/en-us", "Sets directory containing acoustic model files.")
dict = app.StringOpt("dict", "/usr/local/share/pocketsphinx/model/en-us/cmudict-en-us.dict", "Sets main pronunciation dictionary (lexicon) input file..")
lm = app.StringOpt("lm", "/usr/local/share/pocketsphinx/model/en-us/en-us.lm.bin", "Sets word trigram language model input file.")
logfile = app.StringOpt("log", "gortana.log", "Log file to write log to.")
stdout = app.BoolOpt("stdout", false, "Disables log file and writes everything to stdout.")
outraw = app.StringOpt("outraw", "", "Specify output dir for RAW recorded sound files (s16le). Directory must exist.")
)
func main() {
log.SetFlags(0)
app.Action = appRun
app.Run(os.Args)
}
func appRun() {
defer closer.Close()
closer.Bind(func() {
log.Println("Bye!")
})
if err := portaudio.Initialize(); paError(err) {
log.Fatalln("PortAudio init error:", paErrorText(err))
}
closer.Bind(func() {
if err := portaudio.Terminate(); paError(err) {
log.Println("PortAudio term error:", paErrorText(err))
}
})
// Init CMUSphinx
cfg := sphinx.NewConfig(
sphinx.HMMDirOption(*hmm),
sphinx.DictFileOption(*dict),
sphinx.LMFileOption(*lm),
sphinx.SampleRateOption(sampleRate),
)
if len(*outraw) > 0 {
sphinx.RawLogDirOption(*outraw)(cfg)
}
if *stdout == false {
sphinx.LogFileOption(*logfile)(cfg)
}
log.Println("Loading CMU PhocketSphinx.")
log.Println("This may take a while depending on the size of your model.")
dec, err := sphinx.NewDecoder(cfg)
if err != nil {
closer.Fatalln(err)
}
closer.Bind(func() {
dec.Destroy()
})
l := &Listener{
dec: dec,
}
var stream *portaudio.Stream
if err := portaudio.OpenDefaultStream(&stream, channels, 0, sampleFormat, sampleRate,
samplesPerChannel, l.paCallback, nil); paError(err) {
log.Fatalln("PortAudio error:", paErrorText(err))
}
closer.Bind(func() {
if err := portaudio.CloseStream(stream); paError(err) {
log.Println("[WARN] PortAudio error:", paErrorText(err))
}
})
if err := portaudio.StartStream(stream); paError(err) {
log.Fatalln("PortAudio error:", paErrorText(err))
}
closer.Bind(func() {
if err := portaudio.StopStream(stream); paError(err) {
log.Fatalln("[WARN] PortAudio error:", paErrorText(err))
}
})
if !dec.StartUtt() {
closer.Fatalln("[ERR] Sphinx failed to start utterance")
}
log.Println(banner)
log.Println("Ready..")
closer.Hold()
}
type Listener struct {
inSpeech bool
uttStarted bool
dec *sphinx.Decoder
}
// paCallback: for simplicity reasons we process raw audio with sphinx in the this stream callback,
// never do that for any serious applications, use a buffered channel instead.
func (l *Listener) paCallback(input unsafe.Pointer, _ unsafe.Pointer, sampleCount uint,
_ *portaudio.StreamCallbackTimeInfo, _ portaudio.StreamCallbackFlags, _ unsafe.Pointer) int32 {
const (
statusContinue = int32(portaudio.PaContinue)
statusAbort = int32(portaudio.PaAbort)
)
in := (*(*[1 << 24]int16)(input))[:int(sampleCount)*channels]
// ProcessRaw with disabled search because callback needs to be relatime
_, ok := l.dec.ProcessRaw(in, true, false)
// log.Printf("processed: %d frames, ok: %v", frames, ok)
if !ok {
return statusAbort
}
if l.dec.IsInSpeech() {
l.inSpeech = true
if !l.uttStarted {
l.uttStarted = true
log.Println("Listening..")
}
} else if l.uttStarted {
// speech -> silence transition, time to start new utterance
l.dec.EndUtt()
l.uttStarted = false
l.report() // report results
if !l.dec.StartUtt() {
closer.Fatalln("[ERR] Sphinx failed to start utterance")
}
}
return statusContinue
}
func (l *Listener) report() {
hyp, _ := l.dec.Hypothesis()
if len(hyp) > 0 {
log.Printf(" > hypothesis: %s", hyp)
return
}
log.Println("ah, nothing")
}
func paError(err portaudio.Error) bool {
return portaudio.ErrorCode(err) != portaudio.PaNoError
}
func paErrorText(err portaudio.Error) string {
return portaudio.GetErrorText(err)
}
const banner = `
__
/ _ _ _|_ _ _ _
\__)(_)| |_(_|| )(_|
`