关于讯飞云平台申请appId的相关流程在我的另一篇文章java 调用科大讯飞语音听写和语音合成jdk有详细步骤,在此省略,直接上C#调用实时转写的接口代码

websocket调用讯飞接口类:

using IFlyCalc.entity;
using IFlyCalc.utils;
using IFlyCalc.view;
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using WebSocketSharp;namespace IFlyCalc.net
{public class MyWebSocket{private WebSocket ws;private int connectState;//用于更新界面的委托public delegate bool UpdateRetDelegate(string text, bool beSentence);private UpdateRetDelegate updateRetDelegate;private bool beEnd;private string wsUrl = "ws://rtasr.xfyun.cn/v1/ws";private string appId = "*********";//此处请用自己申请的idprivate string apiKey = "*********";//此处请用自己申请的key//参数中的page是需要显示结果的页面对象public MyWebSocket(MyPage page){updateRetDelegate = new UpdateRetDelegate(page.UpdateVoiceResult);//可以放在配置文件中方便修改//wsUrl = ConfigUtil.IniReadValue("rtasr", "url");//appId = ConfigUtil.IniReadValue("rtasr", "appId");//apiKey = ConfigUtil.IniReadValue("rtasr", "apiKey");//System.Diagnostics.Debug.WriteLine("Read config success");}public void InitWebSocket(){try{if (wsUrl == null || wsUrl.Length == 0){System.Diagnostics.Debug.WriteLine("Read config wsUrl fail");return;}if (appId == null || appId.Length == 0){System.Diagnostics.Debug.WriteLine("Read config appId fail");return;}if (apiKey == null || apiKey.Length == 0){System.Diagnostics.Debug.WriteLine("Read config apiKey fail");return;}if (ws == null){string timeStamp = StringUtil.GetTimeStamp();string md5Code = EncryptUtil.GetMd5Code(appId + timeStamp);string hmacsha1Code = EncryptUtil.HMACSHA1Text(md5Code, apiKey);hmacsha1Code = StringUtil.UrlEncode(hmacsha1Code);ws = new WebSocket(wsUrl + "?appid=" + appId + "&ts=" + timeStamp + "&signa=" + hmacsha1Code + "&pd=edu",onClose: OnClose, onMessage: OnMessage, onOpen: OnOpen, onError: OnError);}beEnd = false;if (connectState == 1){return;}connectState = -1;while (true){if (connectState == 0){Thread.Sleep(50);continue;}else if (connectState == 1){System.Diagnostics.Debug.WriteLine("MyWebSocket connect success");return;}System.Diagnostics.Debug.WriteLine("MyWebSocket Connect");if (ws == null){string timeStamp = StringUtil.GetTimeStamp();string md5Code = EncryptUtil.GetMd5Code(appId + timeStamp);string hmacsha1Code = EncryptUtil.HMACSHA1Text(md5Code, apiKey);hmacsha1Code = StringUtil.UrlEncode(hmacsha1Code);ws = new WebSocket(wsUrl + "?appid=" + appId + "&ts=" + timeStamp + "&signa=" + hmacsha1Code + "&pd=edu",onClose: OnClose, onMessage: OnMessage, onOpen: OnOpen, onError: OnError);}ws.Connect();connectState = 0;if (connectState == -1){closeWebsocket();}else if (connectState == 1){System.Diagnostics.Debug.WriteLine("MyWebSocket connect success");return;}}} catch (Exception ex){System.Diagnostics.Debug.WriteLine("InitWebSocket exception:" + ex.Message);}}public void SendByteMsg(byte[] byteMsg){if (ws != null && ws.ReadyState == WebSocketState.Open){System.Diagnostics.Debug.WriteLine("MyWebSocket SendByteMsg");ws.Send(byteMsg);}}public void SendStrMsg(string strMsg){if (ws != null && ws.ReadyState == WebSocketState.Open){System.Diagnostics.Debug.WriteLine("MyWebSocket SendStrMsg");ws.Send(strMsg);beEnd = true;}}public void closeWebsocket(){ws.Close();ws.Dispose();ws = null;connectState = -1;}private Task OnOpen(){System.Diagnostics.Debug.WriteLine("MyWebSocket is opened");return null;}private Task OnClose(CloseEventArgs arg){System.Diagnostics.Debug.WriteLine("MyWebSocket is closed");connectState = -1;return null;}private Task OnMessage(MessageEventArgs args){StringBuilder sb = new StringBuilder();string type = "0";try{string content = args.Text.ReadToEnd();System.Diagnostics.Debug.WriteLine("MyWebSocket receive msg=" + content);IflyRet iflyRet = StringUtil.ParseIflyRet(content);if (iflyRet.code == "0" && iflyRet.data != null && iflyRet.data.Length > 0){RtaData rta = StringUtil.ParseRtaData(iflyRet.data);if (rta != null && rta.cn != null && rta.cn.st != null && rta.cn.st.rt != null && rta.cn.st.rt.Count > 0){type = rta.cn.st.type;WordsList wss = rta.cn.st.rt[0];if (wss != null && wss.ws != null && wss.ws.Count > 0){for (int i = 0; i < wss.ws.Count; i++){Words ws = wss.ws[i];if (ws != null && ws.cw != null && ws.cw.Count > 0){Word word = ws.cw[0];if (word != null && word.wp != "p"){sb.Append(word.w);}}}}}}else if (iflyRet.code == "0"){connectState = 1;}else{connectState = -1;}} catch (Exception ex){System.Diagnostics.Debug.WriteLine("Parse jsonStr exception:" + ex.Message);}string regStr = sb.ToString();if (regStr.Length > 0){System.Diagnostics.Debug.WriteLine("Parse jsonStr centense=" + regStr);//更新UI    (regStr, type);updateRetDelegate(regStr, type == "0");}if (beEnd){closeWebsocket();}return null;}private Task OnError(ErrorEventArgs e){System.Diagnostics.Debug.WriteLine("MyWebSocket get error:" + e.Message);closeWebsocket();return null;}}
}

其中包含的相关工具类:

StringUtil类:

using IFlyCalc.entity;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;namespace IFlyCalc.utils
{public class StringUtil{/// <summary>/// 字节数组转16进制字符串/// </summary>/// <param name="bytes"></param>/// <returns></returns>public static string byteToHexStr(byte[] bytes){string returnStr = "";if (bytes != null){for (int i = 0; i < bytes.Length; i++){returnStr += bytes[i].ToString("X2");}}return returnStr;}/// <summary>/// 获取时间戳/// </summary>/// <returns></returns>public static string GetTimeStamp(){TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);return Convert.ToInt64(ts.TotalSeconds).ToString();}public static RtaData ParseRtaData(string text){try{//StreamReader sr1 = new StreamReader("E:\\code\\jsonData.txt", Encoding.Default);//string jsonStr = sr1.ReadToEnd();StringReader sr = new StringReader(text);JsonSerializer serializer = new JsonSerializer();RtaData rta = (RtaData)serializer.Deserialize(new JsonTextReader(sr), typeof(RtaData));return rta;} catch (Exception ex){System.Diagnostics.Debug.WriteLine("testJson exception:" + ex.Message);}return null;}public static IflyRet ParseIflyRet(string text){try{StringReader sr = new StringReader(text);JsonSerializer serializer = new JsonSerializer();IflyRet iflyRet = (IflyRet)serializer.Deserialize(new JsonTextReader(sr), typeof(IflyRet));return iflyRet;}catch (Exception ex){System.Diagnostics.Debug.WriteLine("testJson exception:" + ex.Message);}return null;}public static string UrlEncode(string str){StringBuilder sb = new StringBuilder();byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)for (int i = 0; i < byStr.Length; i++){sb.Append(@"%" + Convert.ToString(byStr[i], 16));}return (sb.ToString());}}
}

EncryptUtil类:

using System;
using System.Security.Cryptography;
using System.Text;namespace IFlyCalc.utils
{public class EncryptUtil{public static string GetMd5Code(string text){try{//MD5类是抽象类MD5 md5 = MD5.Create();//需要将字符串转成字节数组byte[] buffer = Encoding.Default.GetBytes(text);//加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择byte[] md5buffer = md5.ComputeHash(buffer);string str = null;// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得foreach (byte b in md5buffer){//得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 //但是在和对方测试过程中,发现我这边的MD5加密编码,经常出现少一位或几位的问题;//后来分析发现是 字符串格式符的问题, X 表示大写, x 表示小写, //X2和x2表示不省略首位为0的十六进制数字;str += b.ToString("x2");}Console.WriteLine(str);//202cb962ac59075b964b07152d234b70return str;} catch (Exception e){System.Diagnostics.Debug.WriteLine("GetMd5Code exception:" + e.Message);}return null;}#region HMACSHA1加密  对二进制数据转Base64后再返回/// <summary>/// HMACSHA1加密/// </summary>/// <param name="text">要加密的原串</param>///<param name="key">私钥</param>/// <returns></returns>public static string HMACSHA1Text(string text, string key){try{//HMACSHA1加密HMACSHA1 hmacsha1 = new HMACSHA1{Key = System.Text.Encoding.UTF8.GetBytes(key)};byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);return Convert.ToBase64String(hashBytes);} catch (Exception e){System.Diagnostics.Debug.WriteLine("HMACSHA1Text exception:" + e.Message);}return null;}#endregion}
}

调用MyWebsocket的地方

//按照讯飞文档的要求,从保存的音频数据中每隔40毫秒读取1280byte发送出去
//myWebSocket需要在前面new一个,并且把页面对象带过去,如下
//myWebSocket = new MyWebSocket(page);
private void SendAudioDataToSocket()
{try{while (true){//byteSource是保存麦克风读取到的音频数据if (byteSource == null || byteSource.Count == 0){Thread.Sleep(100);continue;}System.Diagnostics.Debug.WriteLine("byteSource length = " + byteSource.Count);sendIndex++;int remainLen = byteSource.Count - sendIndex * 1280;if (remainLen >= 0){if (sendIndex == 1){myWebSocket.InitWebSocket();}myWebSocket.SendByteMsg(byteSource.GetRange((sendIndex - 1) * 1280, 1280).ToArray());Thread.Sleep(40);if (remainLen == 0){System.Diagnostics.Debug.WriteLine("Send last Audio Data");myWebSocket.SendStrMsg("{\"end\": true}");byteSource.Clear();sendIndex = 0;System.Diagnostics.Debug.WriteLine("Send Audio Data over");}}else{System.Diagnostics.Debug.WriteLine("Send last Audio Data");remainLen = byteSource.Count - (sendIndex - 1) * 1280;myWebSocket.SendByteMsg(byteSource.GetRange((sendIndex - 1) * 1280, remainLen).ToArray());Thread.Sleep(40);//发送结束标志myWebSocket.SendStrMsg("{\"end\": true}");byteSource.Clear();sendIndex = 0;System.Diagnostics.Debug.WriteLine("Send Audio Data over");}}//System.Diagnostics.Debug.WriteLine("byteSource is null, should not send");} catch (Exception ex){System.Diagnostics.Debug.WriteLine("SendAudioDataThread exception:" + ex.Message);}
}

如有不合适的地方,还请多多指正,也希望能帮到大家,^_^

C# 调用讯飞实时语音转写相关推荐

  1. Unity 讯飞实时语音转写(二)—— 接收转写结果

    目录 Unity 讯飞实时语音转写(一)-- 使用WebSocket连接讯飞语音服务器 Unity 讯飞实时语音转写(二)-- 接收转写结果 Unity 讯飞实时语音转写(三)-- 分析转写结果 正文 ...

  2. 讯飞实时语音转写 python3.6.1 可完美运行 解析返回的json字符串 输出所获语音文字

    百度语音识别对录音要求较高(可能是我的问题,sdk和在线api都试过了(滑稽保命)),失败后选择讯飞语音,官方提供的文档是python2版本的 ,经过修改后可在python3中运行 ,解析返回的jso ...

  3. 讯飞智能语音鼠标G50:AI语音、转写翻译、记录截图一键搞定!

    随着互联网的发展,智能鼠标已经成为我们生活和工作中不可或缺的组成部分.然而,鼠标滚轮异响.按键失灵.驱动难用.手感不合适等一系列问题仍时有发生,所以选择一款智能鼠标尤为重要,它不仅可以提高我们的工作效 ...

  4. 讯飞语音测试软件,语音转文字软件哪个好用?讯飞听见一键转写更简单

    语音转文字软件哪个好用?讯飞听见一键转写更简单 2021-05-06 14:53:11 0点赞 1收藏 0评论 作为一个专职记者,我经常要与各种录音文件打交道.每一次采访之后的录音,都需要转写成文字, ...

  5. uni-app 调用讯飞语音。

    uni-app 调用讯飞语音. // //讯飞语音输入接口voice() {var me = this;var options = {};options.engine = 'iFly';options ...

  6. 微信小程序前台调用讯飞语音识别接口

    开整 之前我这边微信小程序调用讯飞的接口还是发一段音频到后台 再去连接讯飞的websocket 真的 贼慢 要是两三秒的还好 稍微长一点就GG 最近突然发现微信小程序有PCM格式了 所以就直接用小程序 ...

  7. 讯飞离线语音命令词识别

    讯飞离线语音命令词识别 强烈推荐 分享一个大神的人工智能教程.零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来! 网址:http://www.captainbed.net/yancyang ...

  8. 开发实战:如何利用实时语音转写技术搞定会议纪要

    前言 在工作中,我们经常需要整理会议内容.输出会议纪要,但是总遇到记录不全.遗漏重点等难题,逼着我们要全程进行会议录音.但发现重听录音又会很浪费时间.影响效率,往往一个小时的会议录音可能需要花费1.5 ...

  9. tts java web_SpringMVC调用讯飞语音合成WebApi示例

    最近讯飞开放了语音合成的WebAPI,相对于之前SDK的方式方便了很多,下面使用SpringMVC写了一个示例,调用讯飞的合成API. XFHelper.java 负责调用讯飞WebAPI接口,处理H ...

  10. Android 讯飞离线语音听写/离线语音识别SDK

    平台 Android + 讯飞离线语音SDK SDK包 下载路径及方法见讯飞官方SDK文档: 离线语音听写 Android SDK 文档 # 在开发者控制台, 可以直接下载SDK. SDK包中的文件结 ...

最新文章

  1. debian6更新网卡驱动
  2. 0079-简单的循环
  3. 证明创建runnable实例和普通类时间一样长
  4. java时间格式24小时制12小时制
  5. 小程序二维码需要发布正式版后才能获取到_IOS14.3正式版发布时间12月15日:苹果ios14.3正式版内容一览[多图]-游戏产业...
  6. 从库找不到对应的被删除的记录
  7. OPPO Reno6 6Pro刷root强解BL锁 oppo reno6 Root教程
  8. Pangolin-最好的SQL注入工具
  9. MSP430单片机与SIM800A调试
  10. 中望cad2012专业破解版
  11. cdn回源php_简述回源原理和CDN缓存
  12. 品今第一届集团迎新分享会,进•无止境
  13. Downward paths(数论,思维)
  14. 【SQLServer】常用时间格式转换
  15. 2022 3.17网易互娱研发岗笔试题锯齿数独题解
  16. 一款性能足够的4.5寸以下的手机
  17. CSS学习笔记7—盒子模型
  18. 免费体验 阿里云智能LOGO帮你解决设计难题
  19. OpenCV4教程——4.1 窗口相关操作
  20. mysql查询95031班人数_MySQL查询练习

热门文章

  1. 如何做好酒店财务管理工作(各部门经理必看)
  2. python cartopy绘制中国区域(包含国界、省界、十段线以及海南诸岛)
  3. 关于Froala Editor的简单使用
  4. Pycharm_EmmyLua断点调试Lua
  5. ramdump crash工具
  6. MATLAB曲线平滑的办法
  7. 文章标题怎么伪原创?火车头标题伪原创插件
  8. BF-5R对讲机改频
  9. opencms的安装
  10. (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.5播放视频文件