-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecording.go
More file actions
133 lines (118 loc) · 2.47 KB
/
recording.go
File metadata and controls
133 lines (118 loc) · 2.47 KB
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
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
"zee/audio"
"zee/beep"
"zee/log"
"zee/transcriber"
"zee/tray"
)
const recordTail = 500 * time.Millisecond
type recordingSession struct {
capture audio.CaptureDevice
transcriberSess transcriber.Session
stop <-chan struct{}
vp *vadProcessor
mon *silenceMonitor
stream bool
mu sync.Mutex
totalFrames uint64
stopped bool
autoClosed atomic.Bool
done chan struct{}
closeOnce sync.Once
}
func newRecordingSession(capture audio.CaptureDevice, stop <-chan struct{}, sess transcriber.Session, silenceClose *atomic.Bool, stream bool) (*recordingSession, error) {
vp, err := newVADProcessor()
if err != nil {
return nil, fmt.Errorf("VAD init: %w", err)
}
return &recordingSession{
capture: capture,
transcriberSess: sess,
stop: stop,
vp: vp,
mon: newSilenceMonitor(silenceClose),
stream: stream,
done: make(chan struct{}),
}, nil
}
func (r *recordingSession) onAudio(data []byte, frameCount uint32) {
r.mu.Lock()
defer r.mu.Unlock()
if r.stopped {
return
}
r.totalFrames += uint64(frameCount)
if len(data) > 0 {
r.transcriberSess.Feed(data)
r.vp.Process(data)
}
}
func (r *recordingSession) Start() error {
r.capture.SetCallback(r.onAudio)
if err := r.capture.Start(); err != nil {
r.capture.ClearCallback()
return err
}
go r.monitorSilence()
go r.awaitStop()
return nil
}
func (r *recordingSession) monitorSilence() {
ticker := time.NewTicker(tickInterval)
defer ticker.Stop()
for {
select {
case <-r.done:
return
case <-ticker.C:
switch r.mon.Tick(r.vp.HasSpeechTick()) {
case SilenceWarn:
log.Info("no_voice_warning")
tray.SetWarning(true)
beep.PlayError()
case SilenceWarnClear:
tray.SetWarning(false)
case SilenceRepeat:
log.Info("silence_during_warning")
beep.PlayError()
case SilenceAutoClose:
log.Info("silence_auto_close")
tray.SetRecording(false)
go beep.PlayEnd()
r.autoClosed.Store(true)
r.close()
return
}
}
}
}
func (r *recordingSession) awaitStop() {
select {
case <-r.stop:
case <-r.done:
return
}
log.Info("recording_stop")
tray.SetRecording(false)
go beep.PlayEnd()
if r.stream {
time.Sleep(recordTail)
}
r.close()
}
func (r *recordingSession) close() {
r.closeOnce.Do(func() { close(r.done) })
}
func (r *recordingSession) Wait() {
<-r.done
r.capture.Stop()
r.capture.ClearCallback()
r.mu.Lock()
r.stopped = true
r.mu.Unlock()
}