精易论坛

标题: C#百度语音识别 [打印本页]

作者: 197076131    时间: 2014-10-27 15:51
标题: C#百度语音识别
  1. <div class="blockcode"><blockquote>private BaiDuSDK baidu = new BaiDuSDK(“你的百度API Key”,“你的百度Secret Key”);
  2.     txtresult.Text = baidu.WavToText(file, "zh");
复制代码

using System;
using 备份器.DLL;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json;

namespace 百度开放测试
{
    public class BaiDuSDK
    {
        private HttpDLL HTTP = new HttpDLL();
        private string token = "";
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="APIKey">百度API Key</param>
        /// <param name="SecretKey">百度Secret Key</param>
        public BaiDuSDK(string APIKey, string SecretKey)
        {
            GetToken( APIKey,SecretKey);

        }
        /// <summary>
        /// Wav识别 ,百度传进来的文件有格式要求,格式不正常通常识别不正确比如:多个不一样文件都是返回一个“的”字
        /// 注意你的音频文件的采样率别搞错,目前百度只支持8000,16000的采样率
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <param name="rate">8000,16000采样率</param>
        /// <param name="lan">中英标识(zh中文 , en英文)</param>
        /// <returns></returns>
        public string WavToText(string filename , string lan)
        {
            if (File.Exists(filename))
            {
                 WavInfo wav =GetWavInfo(filename);
                int rate = int.Parse(wav.dwsamplespersec.ToString());
                //非16bit 位深的直接返回错误
                if (int.Parse(wav.wbitspersample.ToString()) != 16) return "错误:原始语音的录音格式目前只支持评测 8k/16k 采样率 16bit 位深的单声道语音,请自行转换";
                int cuid =11111;//这个随便填
                Byte[] byt = File.ReadAllBytes(filename);
                int len = byt.Length;
                string base64String = Convert.ToBase64String(byt);
                Customer cust = new Customer("wav", rate, 1, token, cuid, len, lan, base64String);
                string jsonStr = JsonConvert.SerializeObject(cust);  //序列化成 Json 格式
                string html = HTTP.Post("http://vop.baidu.com/server_api", jsonStr, "", "https://openapi.baidu.com/");
                try
                {
                    JObject jsons = JObject.Parse(html);
                    if (jsons["err_msg"].Value<string>() == "success.")
                    {

                        return jsons["result"][0].ToString();
                    }
                    else
                    {
                        return jsons["err_msg"].Value<string>();
                    }
                }
                catch (Exception)
                {
                    //异常提示。表示返回的的非JSON数据,意味着参数错误或不支持格式
                    return html;
                }

            }
            else
            {
                return "文件不存在";
            }
        }
        /// <summary>
        /// 取出access_token
        /// </summary>
        private void GetToken(string APIKey,string SecretKey)
        {

            string s = HTTP.GetHtml("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + APIKey + "&client_secret=" + SecretKey,
                "",
                "https://openapi.baidu.com/");
            JObject json = JObject.Parse(s);
             token = json["access_token"].Value<string>();

        }
        public struct WavInfo
        {
            public string groupid;
            public string rifftype;
            public long filesize;
            public string chunkid;
            public long chunksize;
            public short wformattag; //记录着此声音的格式代号,例如WAVE_FORMAT_PCM,WAVE_F0RAM_ADPCM等等。
            public ushort wchannels; //记录声音的频道数。
            public ulong dwsamplespersec;//记录每秒采样率。 16000
            public ulong dwavgbytespersec;//记录每秒的数据量。
            public ushort wblockalign;//记录区块的对齐单位。
            public ushort wbitspersample;//记录每个取样所需的位元数。 位深16
            public string datachunkid;
            public long datasize;
        }
        /// <summary>
        /// 取出WAV头信息
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        private  static WavInfo GetWavInfo(string strpath)
        {
            WavInfo wavInfo = new WavInfo();
            FileInfo fi = new FileInfo(strpath);
            using (System.IO.FileStream fs = fi.OpenRead())
            {
                if (fs.Length >= 44)
                {
                    byte[] bInfo = new byte[44];
                    fs.Read(bInfo, 0, 44);
                    System.Text.Encoding.Default.GetString(bInfo, 0, 4);
                    if (System.Text.Encoding.Default.GetString(bInfo, 0, 4) == "RIFF" && System.Text.Encoding.Default.GetString(bInfo, 8, 4) == "WAVE" && System.Text.Encoding.Default.GetString(bInfo, 12, 4) == "fmt ")
                    {
                        wavInfo.groupid = System.Text.Encoding.Default.GetString(bInfo, 0, 4);
                        System.BitConverter.ToInt32(bInfo, 4);
                        wavInfo.filesize = System.BitConverter.ToInt32(bInfo, 4);
                        //wavInfo.filesize = Convert.ToInt64(System.Text.Encoding.Default.GetString(bInfo,4,4));
                        wavInfo.rifftype = System.Text.Encoding.Default.GetString(bInfo, 8, 4);
                        wavInfo.chunkid = System.Text.Encoding.Default.GetString(bInfo, 12, 4);
                        wavInfo.chunksize = System.BitConverter.ToInt32(bInfo, 16);
                        wavInfo.wformattag = System.BitConverter.ToInt16(bInfo, 20);
                        wavInfo.wchannels = System.BitConverter.ToUInt16(bInfo, 22);
                        wavInfo.dwsamplespersec = System.BitConverter.ToUInt32(bInfo, 24);
                        wavInfo.dwavgbytespersec = System.BitConverter.ToUInt32(bInfo, 28);
                        wavInfo.wblockalign = System.BitConverter.ToUInt16(bInfo, 32);
                        wavInfo.wbitspersample = System.BitConverter.ToUInt16(bInfo, 34);
                        wavInfo.datachunkid = System.Text.Encoding.Default.GetString(bInfo, 36, 4);
                        wavInfo.datasize = System.BitConverter.ToInt32(bInfo, 40);
                    }
                }
            }
            return wavInfo;


        }

    }
    /// <summary>
    /// 定义JSON数据的一个类
    /// </summary>
    public class Customer
    {
        public string format { get; set; }
        public int rate { get; set; }
        public int channel { get; set; }
        public string token { get; set; }
        public int len { get; set; }
        public int cuid { get; set; }
        public string lan { get; set; }
        public string speech { get; set; }
        public Customer()
        {

        }
        /// <summary>
        /// json参数  百度还有其它参数看需求自己加
        /// </summary>
        /// <param name="format">文件类型</param>
        /// <param name="rate">采样率</param>
        /// <param name="channel">声道</param>
        /// <param name="token">access_token 帮助文档说有效期一个月。所以没必要多次申请</param>
        /// <param name="cuid">用户 id,推荐使用 mac 地址/手机IMEI 等类似参数 实际上任何参数都可以</param>
        /// <param name="len">文件长度</param>
        /// <param name="lan">中英标识(zh中文 , en英文)</param>
        /// <param name="speech">文件的base64String编码</param>
        public Customer(string format, int rate, int channel, string token, int cuid, int len, string lan, string speech)
        {
            this.format = format;
            this.rate = rate;
            this.channel = channel;
            this.token = token;
            this.len = len;
            this.speech = speech;
            this.cuid = cuid;
            this.lan = lan;
        }
    }
}


作者: 小落落    时间: 2014-10-27 16:03
学习了
作者: 刘精杰    时间: 2014-12-27 17:17
这个楼主是不是和了一个dll




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4