在C#中使用科大讯飞Web API进行语音合成
最近工作中需要用到讯飞语音合成接口,网上看了下基本都是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();
至此一个完整个方法就好了,是不是很简单。