package services import ( "encoding/base64" "encoding/json" "fmt" "github.com/rdlucklib/rdluck_tools/crypt" "hongze/hz_crm_api/models" "net/url" "strings" "time" "github.com/gorilla/websocket" "hongze/hz_crm_api/utils" ) // 科大讯飞,语音合成 func GetXfVideo(body []byte, savePath string) (err error) { path, err := assembleAuthUrl() if err != nil { return } conn, _, err := websocket.DefaultDialer.Dial(path, nil) if err != nil { return } defer conn.Close() err = conn.WriteMessage(websocket.TextMessage, body) if err != nil { return } for { _, message, err := conn.ReadMessage() if err != nil { fmt.Println("ReadMessage Err:" + err.Error()) return err } item := new(models.XfReciveResult) err = json.Unmarshal(message, &item) if err != nil { fmt.Println("json.Unmarshal Err:" + err.Error()) return err } if item.Code != 0 { goto readWebSocketFail } if item.Code == 0 && item.Data != nil { if item.Data.Status == 1 { audio := item.Data.Audio err = utils.SaveBase64ToFileBySeek(audio, savePath) if err != nil { fmt.Println("文件保存失败", err.Error()) goto readWebSocketFail } } else { audio := item.Data.Audio err = utils.SaveBase64ToFileBySeek(audio, savePath) if err != nil { fmt.Println("文件保存失败", err.Error()) goto webSocketClose //return } fmt.Println("goto close") goto webSocketClose } } } readWebSocketFail: conn.Close() fmt.Println("goto readWebSocketFail") webSocketClose: conn.Close() fmt.Println("goto webSocketClose") return nil } // @hosturl : like wss://iat-api.xfyun.cn/v2/iat // @apikey : apiKey // @apiSecret : apiSecret func assembleAuthUrl() (callUrl string, err error) { ul, err := url.Parse(utils.XfHostUrl) if err != nil { return } //签名时间 date := time.Now().UTC().Format(time.RFC1123) //参与签名的字段 host ,date, request-line signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"} //拼接签名字符串 sign := strings.Join(signString, "\n") fmt.Println("sign:", sign) //签名结果 sha := crypt.HmacSha256EncryptToBase64([]byte(sign), []byte(utils.XfAPISecret)) //构建请求参数 此时不需要urlencoding authUrl := fmt.Sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", utils.XfAPIKey, "hmac-sha256", "host date request-line", sha) //将请求参数使用base64编码 authorization := base64.StdEncoding.EncodeToString([]byte(authUrl)) v := url.Values{} v.Add("host", ul.Host) v.Add("date", date) v.Add("authorization", authorization) //将编码后的字符串url encode后添加到url后面 callUrl = utils.XfHostUrl + "?" + v.Encode() return }