失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > c#对接科大讯飞平台--语音转写

c#对接科大讯飞平台--语音转写

时间:2021-05-12 21:53:44

相关推荐

c#对接科大讯飞平台--语音转写

由于公司需求,需要对录音进行语音识别,并且以歌词的形式展示出来,所以分别对科大讯飞,腾讯的语音识别进行了研究学习,对比过后发现:

目前腾讯还未有声纹识别,不符合需求,pass.

so,选择科大讯飞,研究学习按步骤走:

第一步: 注册账户创建相对应的webAPI,选择语音转写服务 (注册新用户可领取5小时免费转写时间)

第二步: 查看开发文档,下载自己较为熟悉的语言Demo(Java为例)

第三步:将java转成C#

用到的工具类方法:

EncryptHelper.cs

#region MD5加密public static string MD5Encrypt(string encryptString){string returnValue;try{encryptString = "#*f-`" + encryptString + "6^)!mL";MD5 md5 = new MD5CryptoServiceProvider();returnValue = BitConverter.ToString(puteHash(Encoding.UTF8.GetBytes(encryptString))).Replace("-", "");md5.Clear();}catch (Exception){throw;}return returnValue;}public static string MD5(string encryptString){string returnValue;try{MD5 md5 = new MD5CryptoServiceProvider();returnValue = BitConverter.ToString(puteHash(Encoding.Default.GetBytes(encryptString))).Replace("-", "");md5.Clear();}catch (Exception){throw;}return returnValue;}#endregion#region HMACSHA1算法public static string HMACSHA1Base64(string value, string keyStr){Encoding encode = Encoding.UTF8;byte[] byteData = encode.GetBytes(value);byte[] byteKey = encode.GetBytes(keyStr);HMACSHA1 hmac = new HMACSHA1(byteKey);CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);cs.Write(byteData, 0, byteData.Length);cs.Close();return Convert.ToBase64String(hmac.Hash);}#endregion

HttpHelper.cs

public static string HttpPost(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 60, Encoding encoding = null){HttpClient client = null;try{if (url.StartsWith("https")){var handler = new HttpClientHandler();X509Certificate2 cerCaiShang = new X509Certificate2(ApiConfig.CertFile, ApiConfig.CertPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);handler.ClientCertificates.Add(cerCaiShang);handler.PreAuthenticate = true;handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;handler.ClientCertificateOptions = ClientCertificateOption.Manual;handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>{return true;};client = new HttpClient(handler);}else{client = new HttpClient();}if (headers != null){foreach (KeyValuePair<string, string> header in headers){client.DefaultRequestHeaders.Add(header.Key, header.Value);}}if (timeout > 0){client.Timeout = new TimeSpan(0, 0, timeout);}using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8)){if (contentType != null){content.Headers.ContentType = new .Http.Headers.MediaTypeHeaderValue(contentType);}using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result){var result = responseMessage.Content.ReadAsStringAsync().Result;//Log4netUtil.Info("返回结果:" + result);return result;}}}catch (Exception ex){Log4netUtil.Error("Api接口出错了", ex);return "";}finally{client.Dispose();}}public static string HttpPostMulti(string url, Dictionary<string, string> postData, byte[] body, string fileName, Dictionary<string, string> headers = null, string contentType = null, int timeout = 60, Encoding encoding = null){string result = string.Empty;HttpWebRequest request = null;HttpWebResponse response = null;Stream requestStream = null;Stream responseStream = null;try{request = (HttpWebRequest)HttpWebRequest.Create(url);request.Timeout = -1;CookieContainer cookieContainer = new CookieContainer();request.CookieContainer = cookieContainer;request.AllowAutoRedirect = true;request.Method = "POST";//对发送的数据不使用缓存【重要、关键】request.AllowWriteStreamBuffering = false;request.SendChunked = true;//支持分块上传string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");//请求头部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"content\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());//request.AddRange(body.Length);requestStream = request.GetRequestStream();requestStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);requestStream.Write(body, 0, body.Length);//发送其他参数//string Enter = "\r\n";//foreach (var item in postData)//{// StringBuilder sbBody = new StringBuilder($"Content-Disposition: form-data; name=\"{item.Key}\"" + Enter + Enter// + item.Value + Enter);// byte[] postBodyBytes = Encoding.UTF8.GetBytes(sbBody.ToString());// requestStream.Write(postBodyBytes, 0, postBodyBytes.Length);//}requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);response = (HttpWebResponse)request.GetResponse();responseStream = response.GetResponseStream();StreamReader streamReader = new StreamReader(responseStream, System.Text.Encoding.UTF8);result = streamReader.ReadToEnd();//返回信息streamReader.Close();Dispose(null, request, response, requestStream, responseStream);}catch (Exception ex){return "";}finally{Dispose(null, request, response, requestStream, responseStream);}return result;}

JsonHelper.cs

public static JsonHelper Instance { get; } = new JsonHelper();public string Serialize(object obj){return JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });}public string SerializeByConverter(object obj, params JsonConverter[] converters){return JsonConvert.SerializeObject(obj, converters);}public T Deserialize<T>(string input){return JsonConvert.DeserializeObject<T>(input);}public T DeserializeByConverter<T>(string input, params JsonConverter[] converter){return JsonConvert.DeserializeObject<T>(input, converter);}public T DeserializeBySetting<T>(string input, JsonSerializerSettings settings){return JsonConvert.DeserializeObject<T>(input, settings);}private object NullToEmpty(object obj){return null;}

创建model:

public class XunFeiResult{public int ok { get; set; }public int err_no { get; set; }public string failed { get; set; }public string data { get; set; }public string task_id { get; set; }}public class StatusResult{public string desc { get; set; }public int status { get; set; }}

控制台主函数:

using System;using System.Collections.Generic;using System.Security.Cryptography;using System.Text;namespace mon{public class XunFeiSDK{public static string LFASR_HOST = "/api";/*** TODO 设置appid和secret_key*/public static string APPID = "5b752322";public static string SECRET_KEY = "bbe505e1aa69a1b9970460bcdbe65efc";public static string PREPARE = "/prepare";public static string UPLOAD = "/upload";public static string MERGE = "/merge";public static string GET_RESULT = "/getResult";public static string GET_PROGRESS = "/getProgress";/*** 文件分片大小,可根据实际情况调整*/public static int SLICE_SICE = 10485760;// 10Mpublic static Dictionary<string, string> getBaseAuthParam(string taskId){var baseParam = new Dictionary<string, string>();TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);string curTime = Convert.ToInt64(ts.TotalSeconds).ToString();//curTime = "1543760701";string md5 = EncryptHelper.MD5(APPID + curTime).Replace("-", "").ToLower();string signa = EncryptHelper.HMACSHA1Base64(md5, SECRET_KEY);Console.WriteLine($"ts:{curTime} md5:{md5} signa:{signa}");baseParam.Add("app_id", APPID);baseParam.Add("ts", curTime);baseParam.Add("signa", signa);if (!string.IsNullOrEmpty(taskId)){baseParam.Add("task_id", taskId);}return baseParam;}/*** 分片上传*/public static XunFeiResult prepare(System.IO.FileInfo fileInfo){Dictionary<string, string> prepareParam = getBaseAuthParam(null);try{if (fileInfo != null && fileInfo.Exists){prepareParam.Add("file_len", fileInfo.Length + "");prepareParam.Add("file_name", fileInfo.Name);prepareParam.Add("slice_num", (fileInfo.Length / SLICE_SICE) + (fileInfo.Length % SLICE_SICE == 0 ? 0 : 1) + "");}else{Console.WriteLine("指定的文件路径不正确!");}}catch (Exception e){Console.WriteLine(e.Message);// 其他处理异常的代码}/********************TODO 可配置参数********************/// 转写类型//prepareParam.Add("lfasr_type", "0");// 开启分词//prepareParam.Add("has_participle", "true");// 说话人分离//prepareParam.Add("has_seperate", "true");// 设置多候选词个数//prepareParam.Add("max_alternatives", "2");// 是否进行敏感词检出//prepareParam.Add("has_sensitive", "true");// 敏感词类型//prepareParam.put("sensitive_type", "1");// 关键词//prepareParam.put("keywords", "科大讯飞,中国");/****************************************************/var url = LFASR_HOST + PREPARE + "?" + urlPara(prepareParam);string response = HttpHelper.HttpPost(url, null);var result = JsonHelper.Instance.Deserialize<XunFeiResult>(response);Console.WriteLine($"预处理结果:{response}");return result;}public static string urlPara(Dictionary<string, string> prepareParam){var result = "";foreach (var item in prepareParam){result += $"{item.Key}={item.Value}&";}result = result.TrimEnd('&');return result;}/*** 分片上传* * @param taskId 任务id* @param slice 分片的byte数组* @throws SignatureException */public static XunFeiResult uploadSlice(string taskId, string sliceId, byte[] slice, string fileName){Dictionary<string, string> uploadParam = getBaseAuthParam(taskId);uploadParam.Add("slice_id", sliceId);var url = LFASR_HOST + UPLOAD + "?" + urlPara(uploadParam);string response = HttpHelper.HttpPostMulti(url, uploadParam, slice, fileName);if (response == null){throw new Exception("分片上传接口请求失败!");}var result = JsonHelper.Instance.Deserialize<XunFeiResult>(response);Console.WriteLine($"上传结果:{response}");return result;}/*** 文件合并*/public static bool merge(string taskId){Dictionary<string, string> mergeParam = getBaseAuthParam(taskId);var url = LFASR_HOST + MERGE + "?" + urlPara(mergeParam);string response = HttpHelper.HttpPost(url, null);if (string.IsNullOrEmpty(response)){Console.WriteLine("文件合并接口请求失败!");return false;}var result = JsonHelper.Instance.Deserialize<XunFeiResult>(response);if (result.ok == 0){Console.WriteLine("文件合并成功, taskId: " + taskId);return true;}Console.WriteLine("文件合并失败!" + response);return false;}/*** 获取任务进度*/public static XunFeiResult getProgress(string taskId){Dictionary<string, string> progressParam = getBaseAuthParam(taskId);var url = LFASR_HOST + GET_PROGRESS + "?" + urlPara(progressParam);string response = HttpHelper.HttpPost(url, null);if (string.IsNullOrEmpty(response)){Console.WriteLine("获取任务进度接口请求失败!");}var result = JsonHelper.Instance.Deserialize<XunFeiResult>(response);return result;}/*** 获取转写结果*/public static XunFeiResult getResult(string taskId){Dictionary<string, string> resultParam = getBaseAuthParam(taskId);var url = LFASR_HOST + GET_RESULT + "?" + urlPara(resultParam);string response = HttpHelper.HttpPost(url, null);if (string.IsNullOrEmpty(response)){Console.WriteLine("获取任务进度接口请求失败!");}var result = JsonHelper.Instance.Deserialize<XunFeiResult>(response);return result;}}}

结果:

C#签名不能够像Java百分百分片上传成功,原因:MD5解码Default改成utf-8格式。

如果觉得《c#对接科大讯飞平台--语音转写》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。