开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 1986|回复: 2
收起左侧

[C#源码] C#百度语音识别

[复制链接]
结帖率:100% (64/64)
发表于 2014-10-27 15:51:14 | 显示全部楼层 |阅读模式   辽宁省大连市
  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-12-27 17:17:08 | 显示全部楼层   广东省深圳市
这个楼主是不是和了一个dll
回复 支持 反对

使用道具 举报

结帖率:100% (46/46)

签到天数: 3 天

发表于 2014-10-27 16:03:14 | 显示全部楼层   江苏省无锡市
学习了
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 诚聘英才| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 800073686,邮箱:800073686@b.qq.com
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表