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;
        }
    }
}

unity3d微软语音识别httppost失败。安全验证问题的更多相关文章

  1. javaweb从mysql中获取数据验证用户名密码成功跳转,失败重新验证

    要求:validate.jsp页面中获取请求参数(request.getparameter(“name属性的值”)),注意中文参数获取之前要设置请求编码(request.setCharaterEnco ...

  2. 使用actionerror做失败登录验证

    一. 登录页面中放置如下代码: <h4>员工登录</h4> <div style="color:red"> <s:actionerror/ ...

  3. mvc 微软票据验证

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  4. 利用微软Speech SDK 5.1开发语音识别系统主要步骤

    利用微软Speech SDK 5.1开发语音识别系统主要步骤 2009-09-17 10:21:09|  分类: 知识点滴|字号 订阅 微软语音识别分两种模式:文本识别模式和命令识别模式.此两种模式的 ...

  5. 客官,.NETCore无代码侵入的模型验证了解下

    背景 .NETCore下的模型验证相信绝大部分的.NET开发者或多或少的都用过,微软官方提供的模型验证相关的类位于System.ComponentModel.DataAnnotations命令空间下, ...

  6. ASP.NET MVC5----常见的数据注解和验证

    只要一直走,慢点又何妨. 在使用MVC模式进行开发时,数据注解是经常使用的(模型之上操作),下面是我看书整理的一些常见的用法. 什么是验证,数据注解 验证 从全局来看,发现逻辑仅是整个验证的很小的一部 ...

  7. MVC学习系列10---验证系列之服务器端验证

    这篇文章,我将会说到,使用数据注解API来进行服务端验证.ASP.NET MVC 框架在执行的时候,验证所有传递到控制器的数据,如果验证失败就把错误消息,填充到ModelState对象中,并且把这个对 ...

  8. 数据注解和验证 – ASP.NET MVC 4 系列

           不仅在客户端浏览器中需要执行验证逻辑,在服务器端也需要执行.客户端验证能即时给出一个错误反馈(阻止请求发送至服务器),是时下 Web 应用程序所期望的特性.服务器端验证,主要是因为来自网 ...

  9. ASP.NET MVC5(四):数据注解和验证

    前言 用户输入验证的工作,不仅要在客户端浏览器中执行,还要在服务端执行.主要原因是客户端验证会对输入数据给出即时反馈,提高用户体验:服务器端验证,主要是因为不能完全信任用户提供的数据.ASP.NET ...

随机推荐

  1. 5、双指针技巧套路框架——Go语言版

    前情提示:Go语言学习者.本文参考https://labuladong.gitee.io/algo,代码自己参考抒写,若有不妥之处,感谢指正 关于golang算法文章,为了便于下载和整理,都已开源放在 ...

  2. DevOps实战(Docker+Jenkins+Git)

    基于Docker+Jenkins+Git的CI/CD实战 与上一篇随笔:基于 Jenkins+Docker+Git 的CI流程初探 有所不同,该内容更偏向于实际业务的基础需求. 有几点需要注意: 该实 ...

  3. 【Tools】VS搭建Qt开发环境

    00. 目录 @ 目录 00. 目录 01. 概述 02. Visual Studio 2019安装 03. Qt6安装 04. qt-vsaddin插件下载 05. qt-vsaddin插件安装 0 ...

  4. 【LeetCode】1071. Greatest Common Divisor of Strings 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 暴力遍历 日期 题目地址:https://leetc ...

  5. 【LeetCode】7. Reverse Integer 整数反转

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:整数,反转,题解,Leetcode, 力扣,Python, ...

  6. 【LeetCode】646. Maximum Length of Pair Chain 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 贪心算法 日期 题目地址:https://leetc ...

  7. codeforce364(div1.C). Beautiful Set

    C. Beautiful Set time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  8. 1025 - The Specials Menu

    1025 - The Specials Menu    PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: 32 ...

  9. Codeforces1132A——Regular Bracket Sequence(水题)

    Regular Bracket Sequence time limit per test:1 second memory limit per test:256 megabytes input:stan ...

  10. BeanUtils属性转换工具

    commons 包的 BeanUtils 进行属性拷贝性能较差:Spring 的 BeanUtils 性能相对较好. public class A { private String name; pri ...