HTML5录音并调用百度语音识别

HTML5录音借鉴的网上的代码,但是下载下来却无法用,查阅了好多资料,终于在国外某网站上找到原因,原来是js函数废弃了,替换为新的js函数名即可。

HTML5录音的代码:http://www.it165.net/design/html/201406/2651.html

需修改的部分:

原代码:

var HZRecorder = function (stream, config) {
        config = config || {};
        config.sampleBits = config.sampleBits || 8;      //采样数位 8, 16
        config.sampleRate = config.sampleRate || (44100 / 6);   //采样率(1/6 44100)

        var context = new webkitAudioContext();
        var audioInput = context.createMediaStreamSource(stream);
        var recorder = context.createJavaScriptNode(4096, 1, 1);
修改后代码:

var HZRecorder = function (stream, config) {
        config = config || {};
        config.sampleBits = config.sampleBits || 16;      //采样数位 8, 16
        config.sampleRate = config.sampleRate || (16000);   //采样率(1/6 44100)

        var context = new AudioContext();
        var audioInput = context.createMediaStreamSource(stream);
        var recorder = context.createScriptProcessor(4096, 1, 1);


中间有几个地方是修改过的。采样位数改为16是为了后续调用百度语音识别的接口。

百度语音识别接口:http://yuyin.baidu.com/docs/asr/57

下载上面的源码,就可以生成相应的wav,以下是C#调用生成的wav语音文件的测试案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeiPay;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Net;

namespace WebApplication1
{
    public partial class test : System.Web.UI.Page
    {
        string API_Key = "xxxxxx";
        string Secret_Key = "xxxxxx";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TextBox1.Text = GetAccessToken();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            
            string uid = DateTime.Now.ToString("yyyyMMddHHmmss");
            string returnStr = getStrText(uid, TextBox1.Text, "en", "D:\\1.wav", "wav", "16000");
            TextBox2.Text += returnStr + "\n";
        } 

        public string getStrText(string para_API_id, string para_API_access_token,string para_API_language, string para_API_record,string para_format,string para_Hz)
        {
            //方法参数说明:
            //该方法返回值:
            //该方法执行正确返回值是语音翻译的文本,错误是错误号,可以去看百度语音文档,查看对应错误
             
            string strText = null;
            string error = null;
            FileInfo fi = new FileInfo(para_API_record);
            FileStream fs = new FileStream(para_API_record, FileMode.Open);
            byte[] voice = new byte[fs.Length];
            fs.Read(voice, 0, voice.Length);
            fs.Close();
 
            string getTextUrl = "http://vop.baidu.com/server_api?lan=" + para_API_language + "&cuid=" + para_API_id + "&token=" + para_API_access_token;
            HttpWebRequest getTextRequst = WebRequest.Create(getTextUrl) as HttpWebRequest;
 
           /* getTextRequst.Proxy = null;
            getTextRequst.ServicePoint.Expect100Continue = false;
            getTextRequst.ServicePoint.UseNagleAlgorithm = false;
            getTextRequst.ServicePoint.ConnectionLimit = 65500;
            getTextRequst.AllowWriteStreamBuffering = false;*/
 
            getTextRequst.ContentType = "audio /"+para_format+";rate="+para_Hz;
            getTextRequst.ContentLength = fi.Length;
            getTextRequst.Method = "post";
            getTextRequst.Accept = "*/*";
            getTextRequst.KeepAlive = true;
            //serverreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            getTextRequst.Timeout = 30000;//30秒连接不成功就中断 
            using (Stream writeStream = getTextRequst.GetRequestStream())
            {
                writeStream.Write(voice, 0, voice.Length);
            }
            string strJSON = "";
            HttpWebResponse getTextResponse = getTextRequst.GetResponse() as HttpWebResponse;       
            using (StreamReader strHttpText = new StreamReader(getTextResponse.GetResponseStream(), Encoding.UTF8))
            {
                strJSON = strHttpText.ReadToEnd();
            }
            return strJSON;
             
        }



        private string GetAccessToken()
        {
            string url = string.Format("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}", API_Key, Secret_Key);
            string returnStr = HttpUtil.Send("", url);

            Access_Token at = System.Common.JSONConvert.JsonDeserializeBySingleData<Access_Token>(returnStr);
            if (at != null)
            {
                return at.access_token;
            }
            else
            {
                return null;
            }
        }


        

        public class Access_Token
        {
            public string access_token { get; set; }
            public string expires_in { get; set; }
            public string refresh_token { get; set; }
            public string scope { get; set; }
            public string session_key { get; set; }
            public string session_secret { get; set; }
        }

        
    }
}


实际案例应用

另附相似度对比算法及测试程序下载:

/// <summary>
        /// 判断两个字符串的相似度//公式:l = q/(q+r+s);
        /// </summary>
        /// <param name="sourcestring"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Similarity(string a, string b)
        {
            string a1 = "";
            string b1 = "";
            //消除重复
            for (int i = 0; i < a.Length; i++)
            {
                string emtpy = a.Substring(i, 1).ToString();
                if (a1.Length == 0)
                {
                    a1 = emtpy;
                }
                if (a1.IndexOf(emtpy, 0) < 0)
                {
                    a1 += emtpy;
                }
            }
            //消除重复
            for (int i = 0; i < b.Length; i++)
            {
                string emtpy = b.Substring(i, 1).ToString();
                if (b1.Length == 0)
                {
                    b1 = emtpy;
                }
                if (b1.IndexOf(emtpy, 0) < 0)
                {
                    b1 += emtpy;
                }
            }
            //计算相似度
            if (a1.Length >= b1.Length)
            {
                int q = 0;
                for (int i = 0; i < b1.Length; i++)
                {
                    for (int j = 0; j < a1.Length; j++)
                    {
                        if (b1.Substring(i, 1).ToString() == a1.Substring(j, 1).ToString())
                        {
                            q += 1;
                        }
                    }
                }
                System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
                provider.PercentDecimalDigits = 2;//小数点保留几位数.
                provider.PercentPositivePattern = 1;//百分号出现在何处.
                double result = (double)q / (a1.Length + b1.Length - q);//一定要用double类型.
                return result.ToString("P", provider);
            }
            else
            {
                int q = 0;
                for (int i = 0; i < a1.Length; i++)
                {
                    for (int j = 0; j < b1.Length; j++)
                    {
                        if (a1.Substring(i, 1).ToString() == b1.Substring(j, 1).ToString())
                        {
                            q += 1;
                        }
                    }
                }
                System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
                provider.PercentDecimalDigits = 2;//小数点保留几位数.
                provider.PercentPositivePattern = 1;//百分号出现在何处.
                double result = (double)q / (a1.Length + b1.Length - q);//一定要用double类型.
                return result.ToString("P", provider);

            }


        }


案例程序下载:http://download.csdn.net/detail/tcld2269/8745137

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值