关于讯飞云平台申请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 = "*********";//此处请用自己申请的id
private 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(