/
speechtotext.go
70 lines (60 loc) · 1.67 KB
/
speechtotext.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
package speechtotext
import (
"fmt"
"log"
"strings"
"time"
)
type Wrapper interface {
StartContinuous(handler func(event *SDKWrapperEvent)) error
StopContinuous() error
Writer
}
func HandleAudioLink(url string, wrapper Wrapper) (string, error) {
// Download and convert
wavFile, err := handleAudioFileSetup(url)
if err != nil {
return "", err
}
defer deleteFromDisk(wavFile)
stop := make(chan int)
ready := make(chan struct{})
go PumpFileToStream(stop, wavFile, wrapper)
var resultText []string
log.Println("Starting continuous recognition")
err = wrapper.StartContinuous(func(event *SDKWrapperEvent) {
defer event.Close()
switch event.EventType {
case Recognized:
log.Println("Got a recognized event")
resultText = append(resultText, event.Recognized.Result.Text)
case Recognizing:
case Cancellation:
log.Println("Got a cancellation event. Reason: ", event.Cancellation.Reason)
close(ready)
if event.Cancellation.Reason.String() == "Error" {
log.Println("ErrorCode:" + event.Cancellation.ErrorCode.String() + " ErrorDetails: " + event.Cancellation.ErrorDetails)
}
// TODO: If we receive an error here, the writing to the stream should be stopped. Currently that does not seem to happen.
}
})
if err != nil {
return "", err
}
select {
case <-ready:
err := wrapper.StopContinuous()
if err != nil {
log.Println("Error stopping continuous: ", err)
}
case <-time.After(120 * time.Second):
close(stop)
_ = wrapper.StopContinuous()
return "", fmt.Errorf("timeout")
}
defer wrapper.StopContinuous()
if len(resultText) == 0 {
return "", fmt.Errorf("only got empty results")
}
return strings.Join(resultText, " "), nil
}