c# core 6实现讯飞语音听写(流式版)WebAPI 文档

语音听写(流式版)WebAPI 文档 :https://www.xfyun.cn/doc/asr/voicedictation/API.html
官方没有c# api


using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WebSocket4Net;
using System.IO;
using System.Formats.Asn1;
using System.Threading;


namespace ConsoleApp2
{
    /// <summary>
    /// https://www.xfyun.cn/doc/asr/voicedictation/API.html#%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
    /// </summary>
    class Program555语音听写(流式版)
    {
        private const String hostUrl = "wss://ws-api.xfyun.cn/v2/iat"; //http url 不支持解析 ws/wss schema    
        private const String appid = "";//到控制台-语音合成页面获取
        private const String APIKey = "";//到控制台-语音合成页面获取
        private const String APISecret = "";//到控制台-语音合成页面获取
        private const String testFile = @"C:\iat_pcm_16k.pcm";  //测试文件
        private  WebSocket webSocket;
         MemoryStream pcmStream = new MemoryStream();
        public Program555()
        {
            string uri = GetAuthUrl(hostUrl, APIKey);
            webSocket = new WebSocket(uri);
            webSocket.Opened += OnOpened;
            webSocket.Closed += OnClosed;
            webSocket.Error += OnError;
            webSocket.MessageReceived += OnMessageReceived;
            webSocket.Open();

        }
        enum Status
        {
            FirstFrame = 0,
            ContinueFrame = 1,
            LastFrame = 2
        }
        private  volatile Status status = Status.FirstFrame;
        private  void OnError(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }
        public  StringBuilder retsb = new StringBuilder();
        public string resultStr = "";
        private  void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            Console.WriteLine("OnMessageReceived");
            Console.WriteLine(e.Message);
            dynamic msg = JsonConvert.DeserializeObject(e.Message);
            if (msg.code != 0)
            {
                Console.WriteLine($"error => {msg.message},sid => {msg.sid}");
                return;
            }
            var ws = msg.data.result.ws;
            if (ws == null)
            {
                return;
            }
            foreach (var item in ws)
            {
                resultStr = resultStr + item.cw[0].w;
                Console.Write(item.cw[0].w);
            }
            Console.WriteLine();
            if (msg.data.status == 2)
            {
                Console.Write("识别结果:" + resultStr);
                Console.WriteLine("识别结束");
                webSocket.Close();
            }
        }
        private  void OnClosed(object sender, EventArgs e)
        {
            Console.WriteLine("OnClosed");

            string adsf = retsb.ToString();
            Console.WriteLine("OnClosed+结果" + adsf);
        }
        private  void OnOpened(object sender, EventArgs e)
        {
            Console.WriteLine("OnOpened");
            var filestream = File.Open(testFile, FileMode.Open);
            while (true)
            {
                byte[] buffer = new byte[1280];//一次读取5M内容
                int r = filestream.Read(buffer, 0, buffer.Length);//实际读取的有效字节数
                if (r < 1280)//读到最后内容
                {
                    status = Status.LastFrame;

                }
                switch (status)
                {
                    case Status.FirstFrame:
                        {
                            dynamic frame = new JObject();
                            frame.common = new JObject
                        {
                            {"app_id" ,appid }
                        };
                            frame.business = new JObject
                        {
                            { "language","zh_cn" },
                            { "domain","iat" },
                            { "accent","mandarin"},
                            { "dwa","wpgs"}
                        };
                            frame.data = new JObject
                        {
                            { "status",(int)Status.FirstFrame },
                            { "format","audio/L16;rate=16000"},
                            { "encoding","raw" },
                            { "audio",Convert.ToBase64String(buffer)}
                        };
                            webSocket.Send(frame.ToString());
                            status = Status.ContinueFrame;
                        }
                        break;
                    case Status.ContinueFrame:
                        {
                            dynamic frame = new JObject();
                            frame.data = new JObject
                        {
                            { "status",(int)Status.ContinueFrame },
                            { "format","audio/L16;rate=16000"},
                            { "encoding","raw" },
                            { "audio",Convert.ToBase64String(buffer)}
                        };
                            webSocket.Send(frame.ToString());
                        }
                        break;
                    case Status.LastFrame:
                        {
                            dynamic frame = new JObject();
                            frame.data = new JObject
                        {
                            { "status",(int)Status.LastFrame },
                            { "format","audio/L16;rate=16000"},
                            { "encoding","raw" },
                            { "audio",Convert.ToBase64String(buffer)}
                        };
                            webSocket.Send(frame.ToString());
                            break;
                        }
                        break;
                    default:
                        break;
                }
                if (r < 1280)//读到最后内容
                {
                    break;
                }
            }
        }
        private  String GetAuthUrl(String hostUrl, String apiKey)
        {
            Uri url = new Uri(hostUrl);

            var date = DateTime.Now.ToString("R");
            string signature_origin = "host: ws-api.xfyun.cn\ndate: " + date + "\nGET /v2/iat HTTP/1.1";
            HMAC hmac = HMAC.Create("System.Security.Cryptography.HMACSHA256");
            hmac.Key = Encoding.UTF8.GetBytes(APISecret);
            var signature_sha = hmac.ComputeHash(Encoding.UTF8.GetBytes(signature_origin));
            var signature_origin1 = Convert.ToBase64String(signature_sha);
            var authorization_origin = string.Format("api_key=\"{0}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{1}\"", APIKey, signature_origin1);
            string authorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization_origin));
            UriBuilder builder = new UriBuilder()
            {
                Scheme = "wss",
                Host = url.Host,
                Path = url.AbsolutePath,
                Query = $"?authorization={authorization}&date={System.Net.WebUtility.UrlEncode(date)}&host=ws-api.xfyun.cn",
            };
            return builder.ToString();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个 C# WebAPI实现 Header 验证的示例代码: ```csharp public class HeaderAuthenticationFilter : IAuthenticationFilter { private readonly string apiKey = "your_api_key_here"; public bool AllowMultiple => false; public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { // 获取请求头的 Authorization 字段 var authHeader = context.Request.Headers.Authorization; // 如果 Authorization 字段不存在或不是 Bearer 形式的 Token,则返回未授权的错误 if (authHeader == null || !authHeader.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase)) { context.ErrorResult = new AuthenticationFailureResult("Unauthorized", context.Request); return; } // 获取 Token var token = authHeader.Parameter; // 验证 Token 是否正确 if (string.IsNullOrWhiteSpace(token) || !token.Equals(apiKey)) { context.ErrorResult = new AuthenticationFailureResult("Unauthorized", context.Request); return; } // 设置用户身份验证信息 var identity = new GenericIdentity("user"); context.Principal = new GenericPrincipal(identity, new string[] { }); } public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { return Task.FromResult(0); } } public class AuthenticationFailureResult : IHttpActionResult { public string ReasonPhrase { get; private set; } public HttpRequestMessage Request { get; private set; } public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request) { ReasonPhrase = reasonPhrase; Request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; response.ReasonPhrase = ReasonPhrase; return Task.FromResult(response); } } ``` 在上述代码中,我们创建了一个名为 `HeaderAuthenticationFilter` 的类,该类实现了 `IAuthenticationFilter` 接口,用于在 WebAPI 的管道中进行身份验证。我们在 `AuthenticateAsync` 方法中进行身份验证,如果验证失败,则设置 `ErrorResult` 属性返回未授权的错误。如果验证成功,则设置 `Principal` 属性为一个包含用户信息的 `IPrincipal` 对象。最后,我们创建了一个名为 `AuthenticationFailureResult` 的类,该类实现了 `IHttpActionResult` 接口,用于返回错误响应。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值