-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.go
148 lines (121 loc) · 3.89 KB
/
demo.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
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
type TextToSpeechRequest struct {
Text string `json:"text"`
}
type TextToSpeechResponse struct {
AudioURL string `json:"audioUrl"`
}
type WsParam struct {
APPID string
APIKey string
APISecret string
Text string
}
func (w *WsParam) CreateURL() (string, error) {
baseURL := "wss://tts-api.xfyun.cn/v2/tts"
now := time.Now()
date := now.Format(time.RFC1123)
signatureOrigin := fmt.Sprintf("host: ws-api.xfyun.cn\ndate: %s\nGET /v2/tts HTTP/1.1", date)
mac := hmac.New(sha256.New, []byte(w.APISecret))
mac.Write([]byte(signatureOrigin))
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorizationOrigin := fmt.Sprintf(
`api_key="%s", algorithm="hmac-sha256", headers="host date request-line", signature="%s"`,
w.APIKey, signature)
authorization := base64.StdEncoding.EncodeToString([]byte(authorizationOrigin))
v := url.Values{}
v.Add("authorization", authorization)
v.Add("date", date)
v.Add("host", "ws-api.xfyun.cn")
return baseURL + "?" + v.Encode(), nil
}
func websocketConnectAndReceive(wsURL string) ([]byte, error) {
c, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
return nil, fmt.Errorf("dial error: %v", err)
}
defer c.Close()
var audioData []byte
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
fmt.Println("read error:", err)
return
}
var resp map[string]interface{}
err = json.Unmarshal(message, &resp)
if err != nil {
fmt.Println("json unmarshal error:", err)
continue
}
if resp["code"].(float64) != 0 {
fmt.Printf("error code: %v, message: %v\n", resp["code"], resp["message"])
continue
}
data := resp["data"].(map[string]interface{})
audio, err := base64.StdEncoding.DecodeString(data["audio"].(string))
if err != nil {
fmt.Println("base64 decode error:", err)
continue
}
audioData = append(audioData, audio...)
if data["status"].(float64) == 2 {
break
}
}
}()
<-done
return audioData, nil
}
func main() {
router := gin.Default()
router.POST("/texttospeech", func(c *gin.Context) {
var req TextToSpeechRequest
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
wsParam := WsParam{
APPID: "your_app_id",
APIKey: "your_api_key",
APISecret: "your_api_secret",
Text: req.Text,
}
wsURL, err := wsParam.CreateURL()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
audioData, err := websocketConnectAndReceive(wsURL)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
audioFilePath := "./static/audio/demo.pcm"
err = ioutil.WriteFile(audioFilePath, audioData, 0644)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
audioURL := "http://yourdomain.com/static/audio/demo.pcm"
c.JSON(http.StatusOK, TextToSpeechResponse{AudioURL: audioURL})
})
router.Static("/static", "./static")
router.Run