zoukankan      html  css  js  c++  java
  • unity3d微软语音识别httppost失败。安全验证问题

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using UnityEngine;
    
    public class record : MonoBehaviour
    {
        AudioClip audioClip;
        AudioSource audioSource;
    
        public int recordTime=5;
         Use this for initialization
        void Start()
        {
            string[] md = Microphone.devices;
            int mdl = md.Length;
            if (mdl == 0)
            {
                Debug.Log("no microphone found");
            }
        }
    
         Update is called once per frame
        //void Update () {
    
        //}
        public void StartRecordAudio()
        {
            audioSource = GameObject.Find("Canvas/Audio Source").GetComponent<AudioSource>();
            Microphone.End(null);
            audioClip = Microphone.Start(null, false, recordTime, 16000);
            Debug.Log("开始录音.....");
            // if(Microphone.GetPosition())
            if (!Microphone.IsRecording(null))
            {
                Debug.Log("没有声音.....");
                return;
            }
            Microphone.GetPosition(null);
    
        }
        public void StopRecordAudio()
        {
            /***文件读取***
            FileInfo fi = new FileInfo("d:\1.wav");
            FileStream fs = new FileStream("d:\1.wav", FileMode.Open);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();
            ***/
    
    
            Microphone.End(null);
            // byte[] buffer = ConvertAudioClipToPCM16(audioClip);
           byte[] buffer = GetClipData();
            
            HttpWebRequest request = null;
           //request = (HttpWebRequest)HttpWebRequest.Create("https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=ZH-CN&format=detailed");
           request = (HttpWebRequest)HttpWebRequest.Create("http://vop.baidu.com/server_api?lan=zh&cuid=B8-81-98-41-3E-E9&token=24.91d00cdafeef1490ec706f7e2f2659e1.2592000.1524029061.282335-10681472");
    
           request.SendChunked = true;
            request.Accept = @"application/json;text/xml";
            request.Method = "POST";
           request.ProtocolVersion = HttpVersion.Version11;
            request.ContentType = @"audio/wav; codec=audio/pcm; samplerate=16000";
           //request.Headers["Ocp-Apim-Subscription-Key"] = "e8cd273d62c347cb9f64d6b94b94435d";
            request.ContentLength = buffer.Length;
    
            // Send an audio file by 1024 byte chunks
    
            /*
            * Open a request stream and write 1024 byte chunks in the stream one at a time.
            */
            using (Stream requestStream = request.GetRequestStream())
            {
    
    
                requestStream.Write(buffer, 0, buffer.Length);
    
            }
            Debug.Log("Response:");
            string responseString;
            WebResponse response = request.GetResponse();
    
            Debug.Log(((HttpWebResponse)response).StatusCode);
    
            StreamReader sr = new StreamReader(response.GetResponseStream());
    
            responseString = sr.ReadToEnd();
    
    
            Debug.Log(responseString);
    
        }
        public static byte[] ConvertAudioClipToPCM16(AudioClip clip)
        {
            var samples = new float[clip.samples * clip.channels];
            clip.GetData(samples, 0);
            var samples_int16 = new short[samples.Length];
    
            for (var index = 0; index < samples.Length; index++)
            {
                var f = samples[index];
                samples_int16[index] = (short)(f * short.MaxValue);
            }
    
            var byteArray = new byte[samples_int16.Length * 2];
            Buffer.BlockCopy(samples_int16, 0, byteArray, 0, byteArray.Length);
    
            return byteArray;
        }
        /// <summary>
        /// 把录音转换为Byte[]
        /// </summary>
        /// <returns></returns>
        public byte[] GetClipData()
        {
            if (audioClip == null)
            {
                //Debug.LogError("录音数据为空");
                Debug.Log("录音数据为空");
                return null;
            }
    
            float[] samples = new float[audioClip.samples];
    
            audioClip.GetData(samples, 0);
    
    
    
            byte[] outData = new byte[samples.Length * 2];
    
            int rescaleFactor = 32767; //to convert float to Int16   
    
            for (int i = 0; i < samples.Length; i++)
            {
                short temshort = (short)(samples[i] * rescaleFactor);
    
                byte[] temdata = System.BitConverter.GetBytes(temshort);
    
                outData[i * 2] = temdata[0];
                outData[i * 2 + 1] = temdata[1];
            }
            if (outData == null || outData.Length <= 0)
            {
                //Debug.LogError("录音数据为空");
                Debug.Log("录音数据为空");
                return null;
            }
    
            //return SubByte(outData, 0, audioLength * 8000 * 2);
            return outData;
        }
        public void PlayRecordAudio()
        {
            Microphone.End(null);
            audioSource.clip = audioClip;
            audioSource.Play();
        }
        public void EndPlayRecordAudio()
        {
            Microphone.End(null);
            audioSource.Stop();
        }
    }

    1.微软报错百度可以

    无论是读取文件的wav格式还是mcrophone录的音全部报错

    是安全证书问题,mono这个项目总是这样,我以前写Xamarin安卓项目时候也有这个问题。

    只能换www或者UnityWebRequest方式试一试。

    已找到解决方法www可以

    TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates)
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 ()
    Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process ()
    (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()
    Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg)
    Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
    Rethrow as IOException: The authentication or decryption has failed.
    Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
    Rethrow as WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
    System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult)
    System.Net.HttpWebRequest.GetRequestStream ()
    record.StopRecordAudio () (at Assets/record.cs:76)
    UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:165)
    UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
    UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
    UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
    UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
    UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
    UnityEngine.EventSystems.EventSystem:Update()
    

    换成百度倒是会成功

    2.在网页请求下

    微软可以,百度也可以。

    但微软可以识别效果更好一点。在高底噪情况下,百度识别不了,微软可以,可以说是不是一个等级的对手,百度的机器学习也许还需要加强。百度的语句识别也是非常不通顺。

    有条件还是用微软还有Google,据说科大讯飞也不错,但没用过。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace FunctionTest
    {
        public partial class voiceBiying : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                FileInfo fi = new FileInfo("d:\1.wav");
                FileStream fs = new FileStream("d:\1.wav", FileMode.Open);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                HttpWebRequest request = null;
                request = (HttpWebRequest)HttpWebRequest.Create("https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=ZH&format=detailed");
                //request = (HttpWebRequest)HttpWebRequest.Create("http://vop.baidu.com/server_api?lan=zh&cuid=B8-81-98-41-3E-E9&token=24.91d00cdafeef1490ec706f7e2f2659e1.2592000.1524029061.282335-10681472");
    
                request.SendChunked = true;
                request.Accept = @"application/json;text/xml";
                request.Method = "POST";
                request.ProtocolVersion = HttpVersion.Version11;
                request.ContentType = @"audio/wav; codec=audio/pcm; samplerate=16000"; 
                //request.ContentType = @"audio/wav; rate=16000";
                request.Headers["Ocp-Apim-Subscription-Key"] = "e8cd273d62c347cb9f64d6b94b94435d";
                request.ContentLength = buffer.Length;
                // Send an audio file by 1024 byte chunks
                /*
                * Open a request stream and write 1024 byte chunks in the stream one at a time.
                */
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(buffer, 0, buffer.Length);
                }
                TextBox1.Text="Response:";
                string responseString;
                WebResponse response = request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream());
                responseString = sr.ReadToEnd();
                TextBox1.Text+=responseString;
            }
        }
    }
  • 相关阅读:
    Exercise02_09
    Exercise02_05
    Exercise02_01
    Exercise02_03
    Exercise02_07
    web.xml配置详解
    面对不成功的人生
    请不以结婚为目的的恋爱吧
    年轻人能为世界做点什么
    不作就不会活
  • 原文地址:https://www.cnblogs.com/fengmao31/p/13880214.html
Copyright © 2011-2022 走看看