开发目的:前面做语音识别的时候用的百度的API,发现百度API的处理速度比较慢,所以这两天研究了下讯飞的语音识别API,识别速度比百度的快许多
开发中遇到的问题
1.X_Param 参数开始的时候带了空格导致验证不过,原因是讯飞将字符串做了repelce处理
2.讯飞后台设置白名单IP
以下是关键代码:
string path = "語音文件路徑";
var data = File.ReadAllBytes(path);
string base64_audio = Convert.ToBase64String(data);//将二进制的语音文件转base64
string body = "audio="+ System.Web.HttpUtility.UrlEncode(base64_audio);
string url = "http://api.xfyun.cn/v1/service/v1/iat";
string X_Param = ToBase64String("{ \"engine_type\": \"sms16k\", \"aue\": \"raw\"}");//转base64,注意要保去除空格,因为讯飞后台有去空格操作
string X_Time = GetTimeStamp(true);//获取时间戳
HttpContent httpContent = new StringContent(body,Encoding.UTF8, "application/x-www-form-urlencoded");
httpContent.Headers.Add("X-Param", X_Param);
httpContent.Headers.Add("X-CurTime", X_Time);
httpContent.Headers.Add("X-Appid", appid);
httpContent.Headers.Add("X-CheckSum", MD5String(apikey, X_Time, X_Param));
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string responseJson = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseJson);
}
else
{
Console.WriteLine("Error,StatusCode:" + response.StatusCode.ToString());
}
Console.ReadKey();
字符串转base64方法
public static string ToBase64String(string value)
{
value = value.Replace(" ", "");
if (value == null || value == ""){
return "";
}
byte[] bytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(bytes);
}
MD5方法
public static string MD5String(string api_key, string x_time, string x_param)
{
var hash = System.Security.Cryptography.MD5.Create(); //拼接签名数据
var signStr = api_key + x_time + x_param ;
var bytes = Encoding.UTF8.GetBytes(signStr); //使用MD5加密
var md5Val = hash.ComputeHash(bytes); //把二进制转化为大写的十六进制
StringBuilder result = new StringBuilder();
foreach (var c in md5Val) {
result.Append(c.ToString("X2"));
}
return result.ToString().ToLower();
}
获取时间戳方法
public static string GetTimeStamp(bool bflag)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string ret = string.Empty;
if (bflag)
ret = Convert.ToInt64(ts.TotalSeconds).ToString();
else
ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
return ret;
}
网友评论