welcome-voice.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. func handler(w http.ResponseWriter, r *http.Request) {
  19. x_appid := "5c7fcc38"
  20. key := "57d53967332e21d23cf3389bf8129e28"
  21. curtime := strconv.FormatInt(time.Now().Unix(), 10)
  22. tt := make(map[string]string)
  23. tt["aue"] = "lame"
  24. tt["auf"] = "audio/L16;rate=16000"
  25. // tt["voice_name"] = "xiaoyan"
  26. tt["voice_name"] = "aisjiuxu"
  27. param, _ := json.Marshal(tt)
  28. base64_param := base64.StdEncoding.EncodeToString(param)
  29. md5Inst := md5.New()
  30. io.WriteString(md5Inst, key+curtime+base64_param)
  31. checksum := fmt.Sprintf("%x", md5Inst.Sum(nil))
  32. if r.Form == nil {
  33. r.ParseForm()
  34. }
  35. txt := r.FormValue("t")
  36. os.Stdout.WriteString("[" + time.Now().Local().Format("2006-01-02 15:04:05") + "][INFO] 接收到文字: 【" + txt + "】 \n")
  37. if txt == "" {
  38. w.Write([]byte(""))
  39. return
  40. }
  41. var data = url.Values{}
  42. data.Add("text", txt)
  43. req_body := data.Encode()
  44. client := &http.Client{}
  45. req, _ := http.NewRequest("POST", "http://api.xfyun.cn/v1/service/v1/tts", strings.NewReader(req_body))
  46. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  47. req.Header.Set("X-CurTime", curtime)
  48. req.Header.Set("X-Appid", x_appid)
  49. req.Header.Set("X-Param", base64_param)
  50. req.Header.Set("X-CheckSum", checksum)
  51. resp, _ := client.Do(req)
  52. defer resp.Body.Close()
  53. resp_body, _ := ioutil.ReadAll(resp.Body)
  54. w.Header().Add("Content-Type", "audio/mp3")
  55. w.Header().Add("Content-Transfer-Encoding", "binary")
  56. w.Header().Add("Expires", "0")
  57. w.Header().Add("Cache-Control", "no-cache")
  58. respType := resp.Header.Get("content-type")
  59. if strings.Index(respType, "text/plain") > -1 {
  60. os.Stderr.WriteString("[" + time.Now().Local().Format("2006-01-02 15:04:05") + "][ERROR]: " + string(resp_body) + "\n")
  61. w.Write([]byte(""))
  62. return
  63. }
  64. rd := bytes.NewReader(resp_body)
  65. http.ServeContent(w, r, "yinbin.mp3", time.Now().Local(), rd)
  66. }
  67. func main() {
  68. http.HandleFunc("/", handler)
  69. log.Fatal(http.ListenAndServe(":8090", nil))
  70. }