-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsession.go
103 lines (89 loc) · 2.28 KB
/
session.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
package azure_tts
import (
"bytes"
"context"
"encoding/json"
"github.com/gorilla/websocket"
"github.com/qieqieplus/azure-tts-go/protocol"
)
type synthesizeSession struct {
ctx context.Context
sid string
conn *websocket.Conn
}
func (s *synthesizeSession) sendSystemConfig(config *SystemConfig) error {
data, err := newSystemConfigMessage(s.sid, config).Encode()
if err != nil {
return err
}
return s.conn.WriteMessage(websocket.TextMessage, data)
}
func (s *synthesizeSession) sendAudioConfig(config *AudioConfig) error {
data, err := newAudioConfigMessage(s.sid, config).Encode()
if err != nil {
return err
}
return s.conn.WriteMessage(websocket.TextMessage, data)
}
func (s *synthesizeSession) sendTextSynthesis(lang, speaker, text string) error {
data, err := newTextSynthesisMessage(s.sid, lang, speaker, text).Encode()
if err != nil {
return err
}
return s.conn.WriteMessage(websocket.TextMessage, data)
}
func (s *synthesizeSession) sendSSMLSynthesis(ssml string) error {
data, err := newSSMLSynthesisMessage(s.sid, ssml).Encode()
if err != nil {
return err
}
return s.conn.WriteMessage(websocket.TextMessage, data)
}
func (s *synthesizeSession) readLoop(task SynthesizeTask) {
defer func() {
task.Close()
_ = s.conn.Close()
}()
for {
mtype, data, err := s.conn.ReadMessage()
if err != nil {
task.Error <- err
return
}
rd := bytes.NewReader(data)
switch mtype {
case websocket.TextMessage:
pm := &protocol.PlainMessage{}
if err = pm.Decode(rd); err != nil {
task.Error <- err
return
}
switch pm.Header.Get(headerPath) {
case protocol.PathTurnStart:
handleEventAsync(task, pm.Body, &TurnStartEvent{})
case protocol.PathResponse:
handleEventAsync(task, pm.Body, &ResponseEvent{})
case protocol.PathAudioMetadata:
handleEventAsync(task, pm.Body, &AudioMetadataEvent{})
case protocol.PathTurnEnd:
handleEventAsync(task, pm.Body, &TurnEndEvent{})
return
}
case websocket.BinaryMessage:
bm := &protocol.BinaryMessage{}
if err = bm.Decode(rd); err != nil {
task.Error <- err
return
}
task.Audio <- bm.Body
}
}
}
func handleEventAsync[T any](task SynthesizeTask, body []byte, v T) {
err := json.Unmarshal(body, v)
if err != nil {
task.Error <- err
return
}
task.Event <- v
}