1. 程式人生 > >在C#中使用科大訊飛Web API進行語音合成

在C#中使用科大訊飛Web API進行語音合成

.get 接口 style serialize pan python版本 compute serial try

  最近工作中需要用到訊飛語音合成接口,網上看了下基本都是Java,PHP,Python版本的,正好補上C# 版本,代碼比較簡單。

   首先在訊飛開放平臺上創建一個WebApi項目,取到APPID與APIKey,按官方文檔提前準備好一個參數類備用,每個參數是什麽意思,官方文檔上有很詳細的說明:

       public class Parameter
        {
            public string auf { get; set; } = "audio/L16;rate=16000";
            public string aue { get; set; } = "
lame"; public string voice_name { get; set; } = "xiaoyan"; public string speed { get; set; } = "50"; public string volume { get; set; } = "50"; public string pitch { get; set; } = "50"; public string engine_type { get; set; } = "intp65";
public string text_type { get; set; } = "text"; }

   實例化一個Parameter並轉換為Base64:

            Parameter parameter = new Parameter();
            var json_str = JsonConvert.SerializeObject(parameter);
            var base64_str = Convert.ToBase64String(Encoding.UTF8.GetBytes(json_str));

分別創建一個HttpWebRequest與HttpWebResponse,並將請求方式設為POST:

           HttpWebRequest httpwebrequest = null;
           HttpWebResponse httpwebresponse = null;
           httpwebrequest = (HttpWebRequest)WebRequest.Create("http://api.xfyun.cn/v1/service/v1/tts");
httpwebrequest.Method = "POST";

接下來按照文檔設置一些必要參數及請求頭部:   

            String t_s_1970 =TimestampSince1970;
String checksum = GetMD5("你的APIKey" +t_s_1970 + base64_str);//準備好一個checksum備用
httpwebrequest.Headers.Add("X-Param", base64_str);
            httpwebrequest.Headers.Add("X-CurTime", t_s_1970);
            httpwebrequest.Headers.Add("X-Appid", "你的APPID");
            httpwebrequest.Headers.Add("X-CheckSum", checksum);
            httpwebrequest.Headers.Add("X-Real-Ip", "127.0.0.1");
            httpwebrequest.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            httpwebrequest.Headers.Add("charset", "utf-8");

上面準備好之後將要合成的內容寫入到Body裏,並獲取返回結果:

           using (Stream stream = httpwebrequest.GetRequestStream())
            {
                byte[] data = Encoding.UTF8.GetBytes("text=這是中國,那裏也是中國。");//更改生成內容時,text= 要保留
                stream.Write(data, 0, data.Length);
           }
        httpwebresponse = (HttpWebResponse)httpwebrequest.GetResponse();         Stream res_strem = httpwebresponse.GetResponseStream();         if (httpwebresponse.ContentType == "text/plain")//ContentType等於"text/plain"即表示生成失敗,等於"audio/mpeg"即生成成功         {           StreamReader s_reader = new StreamReader(res_strem, Encoding.UTF8);           String a = s_reader.ReadToEnd();         }else{         StreamWriter sw = new StreamWriter(@"D:\abc.mp3");         res_strem.CopyTo(sw.BaseStream);         sw.Flush();         sw.Close();         res_strem.Dispose();
      }  

上面使用到的GetMD5與TimestampSince1970方法體為:

    public static string GetMD5(string source, bool need16 = false, bool toUpper = false)
        {
            var t_toUpper = toUpper ? "X2" : "x2";
            if (string.IsNullOrWhiteSpace(source))
            {
                return string.Empty;
            }
            string t_md5_code = string.Empty;
            try
            {
                MD5 t_md5 = MD5.Create();
                byte[] _t = t_md5.ComputeHash(Encoding.UTF8.GetBytes(source));
                for (int i = 0; i < _t.Length; i++)
                {
                    t_md5_code += _t[i].ToString(t_toUpper);
                }
                if (need16)
                {
                    t_md5_code = t_md5_code.Substring(8, 16);
                }
            }
            catch { }
            return t_md5_code;
        }
public static string TimestampSince1970 => Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();

     至此一個完整個方法就好了,是不是很簡單。

 

在C#中使用科大訊飛Web API進行語音合成