ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# 调用科大讯飞语音转写接口上传音频文件转文字可直接用

2022-07-12 10:01:51  阅读:258  来源: 互联网

标签:string C# 音频文件 Add static 科大 var new dic


 

namespace ConsoleApp0//科大讯飞语音转写接口调用
{
    class Program
    {
        static string appId = "******";
        static string appKey = "*********************";//SecretKey

        static void Main(string[] args)
        {
            var filePath = @"E:\A\OK.wav";
            var taskid = YuChuLi(filePath);
            UploadFile(taskid, filePath);
            HeBingFile(taskid);
            Thread.Sleep(1000 * 60 * 2);
            GetResult(taskid);
            Console.ReadKey();
        }

        public static string md5Encrypt(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] buffer = Encoding.UTF8.GetBytes(str);//将字符串转成字节数组
            byte[] byteArray = md5.ComputeHash(buffer);//调用加密方法
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteArray)//遍历字节数组
            {
                sb.Append(b.ToString("x2"));//将字节数组转成16进制的字符串。X表示16进制,2表示每个16字符占2位
            }
            return sb.ToString();
        }


        public static string HMACSHA1Text(string text, string key)
        {
            //HMACSHA1加密
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(key);

            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);

            var enText = new StringBuilder();
            foreach (byte iByte in hashBytes)
            {
                enText.AppendFormat("{0:x2}", iByte);
            }
            return enText.ToString();

        }

        //再次Base64编码
        public static string HMACSHA1Text2(string text, string key)
        {
            //HMACSHA1加密
            HMACSHA1 hmacsha1 = new HMACSHA1();
            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);

        }

        public static string ToBase64Str(string Str)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(Str);
            return Convert.ToBase64String(b);

        }

        public static string ToPaeameter(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }

        public static string GetSigna()
        {
            TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            long time = (long)mTimeSpan.TotalSeconds;
            var baseString = appId + time.ToString();
            //MD5加密
            var md5Str = md5Encrypt(baseString);
            var signa = HMACSHA1Text2(md5Str, appKey);//HMACSHA1加密兼base64
            return signa;
        }

        public static string GetTs()
        {
            TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            long time = (long)mTimeSpan.TotalSeconds;
            return time.ToString();
        }

        public static byte[] AuthGetFileData(string fileUrl)
        {
            using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                byte[] buffur = new byte[fs.Length];
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(buffur);
                    bw.Close();
                }
                return buffur;
            }
        }
        public static string GetFileSize(long filesize)
        {
            try
            {
                if (filesize < 0)
                {
                    return "0";
                }
                else if (filesize >= 1024 * 1024 * 1024)  //文件大小大于或等于1024MB    
                {
                    return string.Format("{0:0.00} GB", (double)filesize / (1024 * 1024 * 1024));
                }
                else if (filesize >= 1024 * 1024) //文件大小大于或等于1024KB    
                {
                    return string.Format("{0:0.00} MB", (double)filesize / (1024 * 1024));
                }
                else if (filesize >= 1024) //文件大小大于等于1024bytes    
                {
                    return string.Format("{0:0.00} KB", (double)filesize / 1024);
                }
                else
                {
                    return string.Format("{0:0.00} bytes", filesize);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        static string YuChuLi(string filePath)
        {

            FileInfo t = new FileInfo(filePath);
            var fileSize = t.Length;
            var fileName = Path.GetFileName(filePath);
            var url = @"http://raasr.xfyun.cn/api/prepare";
            TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            long time = (long)mTimeSpan.TotalSeconds;
            var baseString = appId + time.ToString();
            //MD5加密
            var md5Str = md5Encrypt(baseString);
            var signa = HMACSHA1Text2(md5Str, appKey);//HMACSHA1加密兼base64
            var dic = new Dictionary<string, string>();
            dic.Add("app_id", $"{appId}");
            dic.Add("signa", $"{signa}");
            dic.Add("ts", time.ToString());
            dic.Add("file_len", $"{fileSize}");
            dic.Add("file_name", $"{fileName}");
            dic.Add("slice_num", "1");
            var result = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpContent httpContent = new FormUrlEncodedContent(dic);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpResponseMessage responseMessage = client.PostAsync(url, httpContent).Result;
                result = responseMessage.Content.ReadAsStringAsync().Result;
            }
            Console.WriteLine(result);
            var taskId = Regex.Match(result, @"(?<=""data"":"").+?(?="")").ToString();
            Console.WriteLine(taskId);
            return taskId;

        }

        public static void UploadFile( string taskId,string filePath)
        {
            var fileName = Path.GetFileName(filePath);
            var uploadUrl = @"https://raasr.xfyun.cn/api/upload";
            var signa2 = GetSigna();
            var ts2 = GetTs();
            using (HttpClient client = new HttpClient())
            {
                var content = new MultipartFormDataContent();
                //content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                var sliceId = GetSliceId();
                content.Add(new StringContent($"{appId}"), "app_id");
                content.Add(new StringContent($"{signa2}"), "signa");
                content.Add(new StringContent($"{ts2}"), "ts");
                content.Add(new StringContent($"{taskId}"), "task_id");
                content.Add(new StringContent($"{sliceId}"), $"slice_id");
                FileStream fStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                content.Add(new StreamContent(fStream, (int)fStream.Length), "content", fileName);
                var res = client.PostAsync(uploadUrl, content).GetAwaiter().GetResult().Content.ReadAsStringAsync().Result;
                Console.WriteLine(res);
            }
        }

        public static void HeBingFile(string taskId)
        {
            var url = @"https://raasr.xfyun.cn/api/merge";
            var signa = GetSigna();
            var ts = GetTs();
            var dic = new Dictionary<string, string>();
            dic.Add("app_id", $"{appId}");
            dic.Add("signa", $"{signa}");
            dic.Add("ts", ts.ToString());
            dic.Add("task_id", $"{taskId}");
            var result = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpContent httpContent = new FormUrlEncodedContent(dic);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpResponseMessage responseMessage = client.PostAsync(url, httpContent).Result;
                result = responseMessage.Content.ReadAsStringAsync().Result;
            }
            Console.WriteLine(result);
            
        }

        public static void GetResult(string taskId)
        {
            var url = "https://raasr.xfyun.cn/api/getProgress";
            var signa = GetSigna();
            var ts = GetTs();
            var dic = new Dictionary<string, string>();
            dic.Add("app_id", $"{appId}");
            dic.Add("signa", $"{signa}");
            dic.Add("ts", ts.ToString());
            dic.Add("task_id", $"{taskId}");
            var result = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpContent httpContent = new FormUrlEncodedContent(dic);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpResponseMessage responseMessage = client.PostAsync(url, httpContent).Result;
                result = responseMessage.Content.ReadAsStringAsync().Result;
            }
            Console.WriteLine(result);
        }

        public static string GetSliceId()
        {
            string sliceId = "aaaaaaaaa`";
            char[] ch = sliceId.ToCharArray();
            for (int i = 0, j = sliceId.Length - 1; i < sliceId.Length && j >= 0; i++)
            {
                if (ch[j] != 'z')
                {
                    ch[j]++;
                    break;
                }
                else
                {
                    ch[j] = 'a';
                    j--;
                    continue;
                }
            }
            return new String(ch);
        }
    }
}

 

标签:string,C#,音频文件,Add,static,科大,var,new,dic
来源: https://www.cnblogs.com/jf-ace/p/16468904.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有