讯飞语音转写.NET版本

吐槽一下,讯飞官方webapi,没有提供.NET版本案例,只有python,java,只好自己摸索,代码不太简洁,这里复习总结一下,权当作做笔记摘抄一样总结一番,也给第一天尝试其他小伙伴一点参考。

检查每个参数名,根据官网提供的api

https://www.xfyun.cn/doc/asr/lfasr/API.html

关于生成分片文件名称,本质是生成类似aaaaaaaa字符串

分片文件本质是,将流一节节发送过去,

有图有真相

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;namespace audio
{/*** 生成slice_id的工具类* 每个转写任务都新建一个SliceIdGenerator来按照分片顺序依次生成slice_id* * @author white**/public class SliceIdGenerator{private const String INIT_STR = "aaaaaaaaa`";private int length = 0;private char[] ch;public SliceIdGenerator(){this.length = INIT_STR.Length;this.ch = INIT_STR.ToCharArray();}/*** 获取sliceId* * @return*/public String getNextSliceId(){for (int i = 0, j = length - 1; i < length && j >= 0; i++){if (ch[j] != 'z'){ch[j]++;break;}else{ch[j] = 'a';j--;continue;}}return new String(ch);}}//{"data":"ec13805cb5e642649027f797ab7e9e31","err_no":0,"failed":null,"ok":0}public class iFlyResult{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; }}//{\"bg\":\"310\",\"ed\":\"1980\",\"onebest\":\"1801. \",\"speaker\":\"0\"}public class StatusResult{public string desc { get; set; }public int status { get; set; }}public class getResult{public string bg { get; set; }public string ed { get; set; }public string onebest { get; set; }public string speaker { get; set; }}// RequestApi api = new RequestApi("88888888", "888888888888888888888888", "");public class ifly{public string task_id="";string detail = "";public void testSigna(){string signa = getSigna("37982798", "1512041814", "888888888888888888888888");}//byte[] buffer,public string BuildParam_prepare(string app_id, string ts, string signa, string filepath,int slice_num){         FileInfo fileInfo = new FileInfo(filepath);//file完整文件路径string file_len = fileInfo.Length.ToString();//kbstring file_name = fileInfo.Name;//string lfasr_type = "0";//string has_participle = "false";//string max_alternatives = "0";//.....其他非必选return "&app_id=" + app_id + "&signa=" + signa + "&ts=" + ts + "&file_len=" + file_len + "&file_name=" + file_name + "&slice_num=" + slice_num;}public string getSigna(string appid,string ts,string key) {string baseString = appid + ts;string targetbase = GenerateMD5(baseString);string signa = HmacSha1Sign(key,targetbase);return signa;}public string GenerateMD5(string txt){using (MD5 mi = MD5.Create()){byte[] buffer = Encoding.Default.GetBytes(txt);//开始加密byte[] newBuffer = mi.ComputeHash(buffer);StringBuilder sb = new StringBuilder();for (int i = 0; i < newBuffer.Length; i++){sb.Append(newBuffer[i].ToString("x2"));}return sb.ToString();}}public string HmacSha1Sign(string secret, string strOrgData){var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(secret));var dataBuffer = Encoding.UTF8.GetBytes(strOrgData);var hashBytes = hmacsha1.ComputeHash(dataBuffer);return Convert.ToBase64String(hashBytes);}//第一步:获取taskidpublic string voice2txt(string app_id,string ts,string signa,string filepath,int slice_num){detail = "";HttpWebRequest request = null;HttpWebResponse response = null;Stream reqStream = null;request = (HttpWebRequest)WebRequest.Create("https://raasr.xfyun.cn/api/prepare");request.Method = "post"; //设置为post请求request.ReadWriteTimeout = 5000;request.KeepAlive = false;request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";byte[] postData = Encoding.UTF8.GetBytes(BuildParam_prepare(app_id,ts,signa,filepath,slice_num)); //使用utf-8格式组装post参数reqStream = request.GetRequestStream();reqStream.Write(postData, 0, postData.Length);response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);string ret = myStreamReader.ReadToEnd();iFlyResult prepareresult = new JavaScriptSerializer().Deserialize<iFlyResult>(ret);return prepareresult.data;           }//第二步:上传数据,RequestApi api = new RequestApi("5e3950f1", "098d577bb69023d205ffaeba2bcf17e6", "");public string uploadSlice(string filepath,bool iszimu){//确保所有分片上传成功,再进行合并SliceIdGenerator sg = new SliceIdGenerator();FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);BinaryReader br = new BinaryReader(fs);byte[] content_s = br.ReadBytes((int)fs.Length);int SLICE_SICE = 10485760;//正好几片bool iszhen = false;int slice_num = (content_s.Length / SLICE_SICE);if (content_s.Length % SLICE_SICE != 0){slice_num += 1;}else {iszhen = true;}string result = "";string app_id = "88888888";string ts = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();string signa = getSigna(app_id, ts, "098d577bb69023d205ffaeba2bcf17e6");//计算出片的数量task_id = voice2txt(app_id, ts, signa, filepath, slice_num);//循环上传每片的流int len = iszhen ? SLICE_SICE : (content_s.Length % SLICE_SICE);byte[] content = null;for (int i = 0; i < slice_num; i++){//如果是最后一个那么取余if (i == slice_num - 1){content = new byte[len];Array.Copy(content_s, (i) * SLICE_SICE, content, 0, len);}else {content = new byte[SLICE_SICE];Array.Copy(content_s, (i) * SLICE_SICE, content, 0, SLICE_SICE);}string BuildParam_uploadSlide = "&app_id=" + app_id + "&signa=" + signa + "&ts=" + ts + "&task_id=" + task_id + "&slice_id=" + sg.getNextSliceId();string rett = HttpPostMulti("https://raasr.xfyun.cn/api/upload?" + BuildParam_uploadSlide, null, content, new FileInfo(filepath).Name); }//iFlyResult uploadresult = new JavaScriptSerializer().Deserialize<iFlyResult>(rett);//int ok = uploadresult.ok;//if (ok==0)//{int o=merge(app_id,ts,signa);if (o==0){result=getProgress(app_id, ts, signa,iszimu); }//}return result;           }//第三步:合并//byte[] buffer,public int merge(string app_id,string ts,string signa){string ret = commonHttpHandle(app_id, ts, signa, "merge"); iFlyResult prepareresult = new JavaScriptSerializer().Deserialize<iFlyResult>(ret);         return prepareresult.ok;}//获取结果//第四步:获取结果//byte[] buffer,public string getProgress(string app_id, string ts, string signa, bool iszimu){//{"data":"{\"status\":2,\"desc\":\"音频合并完成\"}","err_no":0,"failed":null,"ok":0}string ret = commonHttpHandle(app_id, ts, signa, "getProgress");iFlyResult prepareresult = new JavaScriptSerializer().Deserialize<iFlyResult>(ret);StatusResult sr = new JavaScriptSerializer().Deserialize<StatusResult>(prepareresult.data);while (sr.status != 9){Thread.Sleep(6000);ret = commonHttpHandle(app_id, ts, signa, "getProgress");prepareresult = new JavaScriptSerializer().Deserialize<iFlyResult>(ret);sr = new JavaScriptSerializer().Deserialize<StatusResult>(prepareresult.data);}string rett = commonHttpHandle(app_id, ts, signa, "getResult");iFlyResult r = new JavaScriptSerializer().Deserialize<iFlyResult>(rett);List<getResult> listresult = new JavaScriptSerializer().Deserialize<List<getResult>>(r.data);foreach (getResult item in listresult){if (iszimu){detail += Environment.NewLine + "【" + second2hh_mm_ss(item.bg) + "--" + second2hh_mm_ss(item.ed) + "】" + item.onebest + Environment.NewLine;}else{detail += item.onebest;}//detail += item.onebest;}return detail;//if (sr.status == 9)//{//    //{"data":"[{\"bg\":\"310\",\"ed\":\"1980\",\"onebest\":\"1801. \",\"speaker\":\"0\"},{\"bg\":\"1990\",\"ed\":\"4310\",\"onebest\":\"12345678! \",\"speaker\":\"0\"}]","err_no":0,"failed":null,"ok":0}//    string rett = commonHttpHandle(app_id, ts, signa, "getResult");//    iFlyResult r = new JavaScriptSerializer().Deserialize<iFlyResult>(rett);//    List<getResult> listresult = new JavaScriptSerializer().Deserialize<List<getResult>>(r.data);              //    foreach (getResult item in listresult)//    {//        if (iszimu)//        {//            detail += Environment.NewLine + "【" + second2hh_mm_ss(item.bg) + "--" + second2hh_mm_ss(item.ed) + "】" + item.onebest + Environment.NewLine;//        }//        else {//            detail += item.onebest;//        }//        //detail += item.onebest;//    }//    return detail;//}//else {//    Thread.Sleep(60000);//    getProgress(app_id, ts, signa,iszimu);//}//return detail;//return prepareresult.data;}//public string  second2hh_mm_ss(string time){int ranlsecond = int.Parse((int.Parse(time) / 1000).ToString());int hh = ranlsecond / 3600;int mm = (ranlsecond-hh*3600)/60;int ss = ranlsecond - hh * 3600-mm*60;string result = "";         if (hh < 10){result += "0";}result += hh+":";if (mm < 10){result += "0";}result += mm + ":";if (ss < 10){result += "0";}result +=ss ;return  result;}public string commonHttpHandle(string app_id, string ts, string signa,string urltype){string BuildParam_merge = "&app_id=" + app_id + "&signa=" + signa + "&ts=" + ts + "&task_id=" + task_id;HttpWebRequest request = null;HttpWebResponse response = null;Stream reqStream = null;request = (HttpWebRequest)WebRequest.Create("https://raasr.xfyun.cn/api/"+urltype);request.Method = "post"; //设置为post请求request.ReadWriteTimeout = 5000;request.KeepAlive = false;request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";byte[] postData = Encoding.UTF8.GetBytes(BuildParam_merge); //使用utf-8格式组装post参数reqStream = request.GetRequestStream();reqStream.Write(postData, 0, postData.Length);response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);return myStreamReader.ReadToEnd();}public  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;//int SLICE_SICE = 10485760;//byte[] slide = new byte[SLICE_SICE];//Array.Copy(body, slide, body.Length);//Array.Copy(body, slide, slide.Length);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);//requestStream.Write(slide, 0, slide.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();requestStream.Dispose();responseStream.Dispose();//Dispose(null, request, response, requestStream, responseStream);}catch (Exception ex){return "";}finally{requestStream.Dispose();responseStream.Dispose();//Dispose(null, request, response, requestStream, responseStream);}return result;}}
}

调用:

 var ifly = new ifly();string result = ifly.uploadSlice(filePath, true);string txtpath = filePath.Substring(0, filePath.Length - 3) + "txt";translate(result, txtpath);

替换里面API涉及的关于申请用户的关键参数值

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/44308.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

蓝桥杯省赛真题——最少刷题数

2022年第13届省赛&#xff0c;蓝桥杯真题。 (本笔记适合初通 Python 的 coder 翻阅) 【学习的细节是欢悦的历程】 Python 官网&#xff1a;https://www.python.org/ Free&#xff1a;大咖免费“圣经”教程《 python 完全自学教程》&#xff0c;不仅仅是基础那么简单…… 地址&…

派发奖学金

根据输入的分数成绩列表&#xff0c;给排名前10派发奖学金。 (本笔记适合能熟练应用列表数据结构的 coder 翻阅) 【学习的细节是欢悦的历程】 Python 官网&#xff1a;https://www.python.org/ Free&#xff1a;大咖免费“圣经”教程《 python 完全自学教程》&#xff0c;不仅…

New Bing 全面开放?我看未必

前段时间大家应该都被ChatGPT刷屏了&#xff0c;其实就回答来说New Bing 才是最厉害的&#xff0c;因为它底层使用了ChatGPT 并且可以支持联网查询数据&#xff0c;回答中还能支持看到出处&#xff0c;方便确认其真实性。 New Bing 是微软基于 OpenAI ChatGPT 技术开发的新一代…

微软Bing突然爆炸级更新!无需等待人人可用,答案图文并茂,网友:逼 ChatGPT 放大招?...

杨净 明敏 发自 凹非寺量子位 | 公众号 QbitAI 所有人都能上手微软Bing了&#xff01; 今天&#xff0c;微软突然官宣全面开放BingChat&#xff1a; 无需任何等待。只需注册一个账户&#xff0c;首页即可体验。 更关键的是&#xff0c;还有一大堆堪称“家底”的新功能来袭&…

90后韩尚佑晋升抖音总裁

上一篇&#xff1a;程序员变高危职位&#xff01;又一个删库跑路进去了 近日&#xff0c;字节跳动发生组织架构调整。 抖音副总裁韩尚佑成为抖音部门负责人&#xff0c;统筹管理抖音、中国直播、生活服务业务线。抖音旗下各业务板块负责人改向韩尚佑汇报&#xff0c;包括基础产…

能取代90%的人的工作的ChatGpt到底牛在哪?

人工智能研究实验室OpenAI在2022年11月30日发布了自然语言生成模型ChatGPT&#xff0c;上线两个月就已经超过一亿用户&#xff0c;成为了人工智能界当之无愧的超级大网红。ChatGPT凭借着自身强大的拟人化及时应答能力迅速破圈&#xff0c;引起了各行各业的热烈讨论。简单来说Ch…

git clone出现 fatal: unable to access ‘https://github.com/...‘的两种解决方法

利用gitee下载github中开放的源码 方法一&#xff1a; step 1&#xff1a; step 2&#xff1a; step 3&#xff1a; 方法二 step 1: step 2&#xff1a; step 3: step 4方法一&#…

chatgpt赋能python:Python如何变成App:一篇SEO文章

Python如何变成App&#xff1a;一篇SEO文章 Python作为一种高级编程语言&#xff0c;广泛应用于科学、数据分析、Web开发以及机器学习等领域。但是&#xff0c;Python如何用于移动应用程序的开发呢&#xff1f;本文将介绍Python变成App的方法以及与之相关的SEO技术。 什么是P…

chatgpt赋能python:PythonGUI开发的介绍

Python GUI开发的介绍 了解GUI GUI&#xff08;图形用户界面&#xff09;是一种计算机与人之间进行交互的方式&#xff0c;它使用视觉元素如窗口、按钮、滑块、图像等替代了命令行交互模式。GUI让用户可以更快速、高效、舒适地完成任务&#xff0c;位于操作系统的图形外壳上&…

好文转载 ChatGPT被淘汰了?Auto-GPT到底有多强

大家好&#xff0c;我是可夫小子&#xff0c;关注AIGC、读书和自媒体。解锁更多ChatGPT、AI绘画玩法。 说Auto-GPT淘汰了ChatGPT了&#xff0c;显然是营销文案里面的标题党。毕竟它还是基于ChatGPT的API&#xff0c;某种意义只是基于ChatGPT能力的应用。但最近&#xff0c;Auto…

热闹!热闹!一觉醒来,ChatGPT被淘汰成了过气明星?

AutoGPT&#xff1a;AI领域的新成员 近日&#xff0c;AI领域似乎出现了一种新的趋势&#xff1a;自主人工智能。 最近一个名为AutoGPT的研究开始走进大众视野。特斯拉前AI总监、刚刚回归OpenAI的Andrej Karpathy也为其大力宣传&#xff0c;并在推特赞扬&#xff1a;“AutoGPT是…

只见新人笑,不见旧人哭 ChatGPT淘汰了多少产品?快来了解!

ChatGPT作为目前世界上最先进的人工智能聊天工具&#xff0c;其GPT模型就是一种自然语言处理&#xff08;NLP&#xff09;模型&#xff0c;使用多层变换器&#xff08;Transformer&#xff09;来预测下一个单词的概率分布&#xff0c;通过训练在大型文本语料库上学习到的语言模…

谷歌翻译插件imtranslator安装使用步骤

在阅读网页的时候会遇到一些看不懂的英文&#xff0c;这时候再去打开翻译软件去翻译难免扫兴&#xff1b;所以我需要一款实时划词翻译的软件&#xff01; 这里介绍一款我在用的谷歌插件&#xff1a;imtranslator 步骤&#xff1a; 1.(科学上网)在谷歌应用商城下载imtranslator插…

推荐一个谷歌浏览器插件:划词翻译

地址&#xff1a;划词翻译插件 最近在看一些英文文档&#xff0c;遇到了一些词汇不认识&#xff0c;在谷歌浏览器上找到了这个翻译插件 谷歌浏览器自己有一个全文翻译的功能&#xff0c;对于一些技术类文档&#xff0c;有些词如果翻译错误了就会闹出笑话来&#xff0c;限于对…

【Google谷歌翻译】Zotero翻译插件中的引擎不可用,解决

配置文件后Zotero的Google翻译引擎可用 &#xff08;Win10系统&#xff09; 以记事本方式打开C:\Windows\System32\drivers\etc\hosts 在最后一行加入203.208.39.194 translate.googleapis.com&#xff0c;然后保存Zotero翻译插件中的“谷歌API&#xff08;中国可用&#xff09…

谷歌浏览器翻译插件安装步骤

首先下载最新版谷歌浏览器&#xff0c;这样能保证和我的操作界面一样&#xff0c;因为我的是最新版本的谷歌浏览器 一、先下载可用的翻译插件 插件下载地址&#xff1a;https://download.csdn.net/download/weixin_44743624/87631622 下载完成后解压&#xff0c;然后打开谷歌…

Chrome浏览器使用谷歌翻译插件的正确方法

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

win10中cmd拒绝访问授权

CMD控制台提示“请求的操作需要提升”怎么解决呢?通常导致此类情况产生的重要原因是操作权限不足所造成的&#xff0c;对此可以通过以下方法来解决。 方法一&#xff1a; 1、在CMD控制台界面中进行操作时&#xff0c;当出现“请求的操作需要提升”的提示时&#xff0c;我们需要…

抖音抓包获取cookie

抓包获取抖音用户cookie 获取抖音cookie目前实践测试两种方式&#xff1a; ​ 一&#xff1a;扫描抖音开放平台二维码&#xff0c;扫码后获取cookie ​ 二&#xff1a;利用fiddler抓包工具对雷电模拟器进行抓包获取cookie 今天就分享一下利用fiddler抓包工具获取cookie 一、准…

抖音用户搜索接口

我还是通过手机模拟器来进行抓包。下面这个是get请求搜索接口&#xff0c;返回的是相关搜索信息。 只是一个简单的介绍。后面有搜索用户的POST接口&#xff0c;可以获取到用户id&#xff0c;以便尽一步操作。 搜索相关用户的接口&#xff1a; 点击使用浏览器访问。 所以可以根…