123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package service
-
- import (
- "bytes"
- "crypto/md5"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "errors"
- "fmt"
- "io/ioutil"
- "mime/multipart"
- "net/http"
- "net/url"
- "strings"
- "time"
- )
-
- // Xfyun 讯飞云调用对象
- type Xfyun struct {
- URL string
- ID string
- KEY string
- }
-
- // XfyunResult 讯飞云返回结果
- type XfyunResult struct {
- Code string `json:"code"`
- Data string `json:"data"`
- Desc string `json:"desc"`
- Sid string `json:"sid"`
- }
-
- // XfyunParam 讯飞云请求参数
- type XfyunParam struct {
- Aue string `json:"aue"`
- EngineType string `json:"engine_type"`
- }
-
- // SuccessCode 讯飞云成功代码
- const SuccessCode = "success"
-
- // SpeechToText speech to text input File
- func SpeechToText(file multipart.File, lang string, rateStr string) (string, error) {
- xfyun := Xfyun{
- URL: "http://api.xfyun.cn/v1/service/v1/iat",
- ID: "5bbaeda1",
- KEY: "25c68c82b45309d35a7f14069107746b",
- }
- wav, err := ioutil.ReadAll(file)
-
- if err != nil {
- return "", err
- }
- //
- base64Audio := base64.StdEncoding.EncodeToString(wav)
- u := url.Values{}
- u.Set("audio", base64Audio)
- body := u.Encode()
- xfyunParam := XfyunParam{
- Aue: "raw",
- EngineType: "sms",
- }
-
- if lang != "zh" {
- xfyunParam.EngineType += "-en"
- }
- if rateStr == "8" {
- xfyunParam.EngineType += "8k"
- } else {
- xfyunParam.EngineType += "16k"
- }
- xfyunParamString, _ := json.Marshal(xfyunParam)
-
- fmt.Println(string(xfyunParamString))
-
- xParam := base64.StdEncoding.EncodeToString(xfyunParamString)
- xTime := time.Now().Unix()
-
- h := md5.New()
- h.Write([]byte(fmt.Sprintf("%s%d%s", xfyun.KEY, xTime, xParam)))
- xChecksum := hex.EncodeToString(h.Sum(nil))
-
- client := &http.Client{}
-
- req, _ := http.NewRequest("POST", xfyun.URL, bytes.NewBuffer([]byte(body)))
-
- req.Header.Set("Accept-Encoding", "identity")
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Add("X-Appid", xfyun.ID)
- req.Header.Add("X-CurTime", fmt.Sprintf("%d", xTime))
- req.Header.Add("X-Param", xParam)
- req.Header.Add("X-CheckSum", xChecksum)
-
- resp, err := client.Do(req)
- if err != nil {
- return "", nil
- }
-
- html, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return "", err
- }
-
- xfyunResult := XfyunResult{}
- err = json.Unmarshal(html, &xfyunResult)
- if err != nil {
- return "", nil
- }
- var text string
- if xfyunResult.Desc == SuccessCode {
- text = xfyunResult.Data
- } else {
- err = errors.New(xfyunResult.Desc)
- return "", err
- }
-
- return strings.TrimSpace(text), nil
- }
|