http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 30063|回复: 23

[C#语言基础] C#百度语音识别

[复制链接]
发表于 2014-6-28 02:19:08 | 显示全部楼层 |阅读模式
[C#] 纯文本查看 复制代码
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;
        }
    }
}

百度申请KEY很简单一天就过,没事写着玩
外部调用         
[C#] 纯文本查看 复制代码
  private BaiDuSDK baidu = new BaiDuSDK(“你的百度API Key”,“你的百度Secret Key”);
      txtresult.Text = baidu.WavToText(file, "zh");

11111.png

本帖被以下淘专辑推荐:



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2014-6-28 08:04:45 | 显示全部楼层
这个不错,支持一下
发表于 2014-6-28 08:58:06 | 显示全部楼层
我能说楼主你的测试内容亮瞎眼了吗。。。
支持。。
发表于 2014-6-28 10:57:37 | 显示全部楼层
请问一下你的 HttpDLL 是哪个命名空间
发表于 2014-6-28 12:49:28 | 显示全部楼层
强烈支持楼主ing……
发表于 2014-6-28 13:45:10 | 显示全部楼层
膜拜中……
回复

使用道具 举报

 楼主| 发表于 2014-6-28 19:02:14 | 显示全部楼层
本帖最后由 写一首诗 于 2014-6-29 00:58 编辑
lechenging 发表于 2014-6-28 10:57
请问一下你的 HttpDLL 是哪个命名空间

HttpDLL  就是HttpWebRequest请求,只不过是我自己封装的,你可以用苏飞的类。
发表于 2014-6-29 11:29:08 | 显示全部楼层
学习学习
回复

使用道具 举报

发表于 2014-6-30 16:10:37 | 显示全部楼层
眼前一亮啊。
发表于 2014-7-2 00:12:09 | 显示全部楼层
有意思
回复

使用道具 举报

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

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-23 15:17

© 2014-2021

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