-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsynthesize.go
101 lines (86 loc) · 2.15 KB
/
synthesize.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
package azure_tts
import (
"context"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
)
type Synthesizer struct {
subConfig *SubscriptionConfig
systemConfig *SystemConfig
audioConfig *AudioConfig
ctx context.Context
}
func NewSynthesizer(ctx context.Context, sub *SubscriptionConfig) *Synthesizer {
return &Synthesizer{
subConfig: sub,
systemConfig: NewDefaultSystemConfig(),
audioConfig: NewDefaultAudioConfig(),
ctx: ctx,
}
}
func (s *Synthesizer) newSession() (*synthesizeSession, error) {
endpoint := getWebsocketEndpoint(s.subConfig.Region)
queries := url.Values{
// headerAuth: []string{fmt.Sprintf("Bearer %s", ...)},
headerConnectionId: []string{getGUID()},
}
wssUrl := endpoint + "?" + queries.Encode()
dialer := websocket.Dialer{
HandshakeTimeout: 10 * time.Second,
EnableCompression: true,
}
conn, _, err := dialer.DialContext(s.ctx, wssUrl, http.Header{
headerEncoding: []string{acceptEncoding},
headerKey: []string{s.subConfig.Key},
})
if err != nil {
return nil, err
}
return &synthesizeSession{
ctx: s.ctx,
sid: getGUID(),
conn: conn,
}, nil
}
func (s *Synthesizer) speakAsync(sender func(sess *synthesizeSession) error) (task SynthesizeTask) {
var (
sess *synthesizeSession
err error
)
task = newSynthesizeTask(s.ctx)
defer func() {
if err != nil {
task.Error <- err
task.Close()
}
}()
if sess, err = s.newSession(); err != nil {
return
}
if err = sess.sendSystemConfig(s.systemConfig); err != nil {
return
}
if err = sess.sendAudioConfig(s.audioConfig); err != nil {
return
}
if err = sender(sess); err != nil {
return
}
go sess.readLoop(task)
return
}
func (s *Synthesizer) SetConfig(audioConfig *AudioConfig) {
s.audioConfig = audioConfig
}
func (s *Synthesizer) SpeakTextAsync(lang, speaker, text string) (task SynthesizeTask) {
return s.speakAsync(func(sess *synthesizeSession) error {
return sess.sendTextSynthesis(lang, speaker, text)
})
}
func (s *Synthesizer) SpeakSSMLAsync(ssml string) (task SynthesizeTask) {
return s.speakAsync(func(sess *synthesizeSession) error {
return sess.sendSSMLSynthesis(ssml)
})
}