C#基于ClientWebSocket实现讯飞文本转语音v2版本

  1  private static string app_id = ConfigurationManager.AppSettings["Xunfei_App_id"];
  2  private static string api_key =  ConfigurationManager.AppSettings["Xunfei_Api_Key"];
  3  private static string api_secret = ConfigurationManager.AppSettings["Xunfei_Api_Secret"]; 
  4  private bool SendWebSocket(string text,string filePath)
  5         {
  6             try
  7             {
  8                 //请求参数
  9                 var param = new
 10                 {
 11                     common = new { app_id = app_id },
 12                     business = new
 13                     {
 14                         aue = "raw",
 15                         sfl = 1,
 16                         auf = "audio/L16;rate=16000",
 17                         vcn = "aisjinger",
 18                         speed = 50,
 19                         volume = 70,
 20                         pitch = 50,
 21                         bgs = 1,
 22                         tte = "UTF8"
 23                     },
 24                     data = new
 25                     {
 26                         status = 2,
 27                         text = Convert.ToBase64String(Encoding.UTF8.GetBytes(text))
 28                     }
 29                 };
 30                 string sendMsg = JsonConvert.SerializeObject(param);
 31                 //随便定义
 32                 string host = "localhost:8080";
 33                 var date = DateTime.UtcNow.ToString("R");
 34 
 35                 var signature_ori = $"host: {host}\ndate: {date}\nGET /v2/tts HTTP/1.1";
 36 
 37                 string signature = hmacsha256(signature_ori, api_secret);
 38 
 39                 //获取签名
 40                 var authorization_ori = $"api_key=\"{api_key}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{signature}\"";
 41                 byte[] buffer = Encoding.UTF8.GetBytes(authorization_ori);
 42                 var authorization = Convert.ToBase64String(buffer);
 43 
 44                 //获取socket请求地址
 45                 var url = $"wss://tts-api.xfyun.cn/v2/tts?authorization={authorization}&date={date}&host={host}";
 46 
 47                 System.Threading.CancellationToken _cancel = new System.Threading.CancellationToken();
 48                 ClientWebSocket clientWebSocket = new ClientWebSocket();
 49                 clientWebSocket.ConnectAsync(new Uri(url), _cancel).Wait();
 50                 clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(sendMsg)), WebSocketMessageType.Text, true, _cancel).Wait();
 51                 string str = string.Empty;
 52                 while (clientWebSocket.State == System.Net.WebSockets.WebSocketState.Open)
 53                 {
 54                     var result = new byte[1024*4];
 55                     clientWebSocket.ReceiveAsync(new ArraySegment<byte>(result), _cancel).Wait();//接受数据
 56                     var lastbyte = ByteCut(result, 0x00);
 57                     str += Encoding.UTF8.GetString(lastbyte, 0, lastbyte.Length);
 58                 }
 59                 clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,string.Empty ,_cancel).Wait();
 60                 string[] arry = str.Split(new string[] { "}}" }, StringSplitOptions.None).Where(t => !string.IsNullOrEmpty(t)).ToArray();
 61 
 62                 using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Append))
 63                 {
 64                     foreach (var item in arry)
 65                     {
 66                         string json = item + "}}";
 67                         dynamic jsonData = JsonConvert.DeserializeObject(json) as dynamic;
 68                         int code = jsonData.code;
 69 
 70                         if (code != 0)
 71                         {
 72                             //合成失败
 73 
 74                         }
 75                         else
 76                         {
 77                             _result = jsonData.data.audio;
 78                             byte[] buf = Convert.FromBase64String(_result);
 79                             stream.Write(buf, 0, buf.Length);
 80                         }
 81                     }
 82                 }
 83                 return true;
 84             }
 85             catch(Exception ex)
 86             {
 87                 return false;
 88             }
 89         }
 90 
 91  private byte[] ByteCut(byte[] buf, byte cut = 0x00)
 92         {
 93             var list = new List<byte>();
 94             list.AddRange(buf);
 95             for (var i = list.Count - 1; i >= 0; i--)
 96             {
 97                 if (list[i] == cut)
 98                 {
 99                     list.RemoveAt(i);
100                 }
101                 else
102                 {
103                     break;
104                 }
105             }
106             var lastbyte = new byte[list.Count];
107             for (var i = 0; i < list.Count; i++)
108             {
109                 lastbyte[i] = list[i];
110             }
111             return lastbyte;
112         }

 

posted @ 2020-10-26 17:34  comicwang  阅读(530)  评论(0编辑  收藏  举报