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. navicat模型分享方法

    一. 查看模型保存路径选中模型如:<app-订单模型>,点击右键,对象信息,可以看到文件位置:C:\Users\Administrator\Documents\Navicat\Premiu ...

  2. JAVA连接redis报错 :stop-writes-on-bgsave-error option

    (error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist o ...

  3. 【九度OJ】题目1178:复数集合 解题报告

    [九度OJ]题目1178:复数集合 解题报告 标签(空格分隔): 九度OJ http://ac.jobdu.com/problem.php?pid=1178 题目描述: 一个复数(x+iy)集合,两种 ...

  4. 【九度OJ】题目1177:查找 解题报告

    [九度OJ]题目1177:查找 解题报告 标签(空格分隔): 九度OJ http://ac.jobdu.com/problem.php?pid=1177 题目描述: 读入一组字符串(待操作的),再读入 ...

  5. Docker 与 K8S学习笔记(二)—— 容器核心知识梳理

    本篇主要对容器相关核心知识进行梳理,通过本篇的学习,我们可以对容器相关的概念有一个全面的了解,这样有利于后面的学习. 一.什么是容器? 容器是一种轻量级.可移植.自包含的软件打包技术,使应用程序可以在 ...

  6. 【C++】指针初始化

    1.Node * p:if(p)//报错 2.Node * p=NULL;if(p)//不报错 注意把指针初始化,否则指针将指向任意位置

  7. 解决opencv:AttributeError: 'NoneType' object has no attribute 'copy'

    情况一: 路径中有中文,更改即可 情况二:可以运行代码,在运行结束时显示 AttributeError: 'NoneType' object has no attribute 'copy' 因为如果是 ...

  8. Android物联网应用程序开发(智慧城市)—— 摄像头监控界面开发

    效果: 布局代码: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: ...

  9. 编写Java程序,演练静态内部类应用

    返回本章节 返回作业目录 需求说明: 创建一个Person类,在该类中定义一个Home静态内部类,并在这个Home类中定义一个显示Home相关信息的方法. 在Person类中设置一个Home类型属性对 ...

  10. 关于PaddleSharp GPU使用 常见问题记录

    在安装NVIDIA驱动过程中遇到一系列问题,记录如下! 附上PaddleSharp地址,大家喜欢可以关注 根据PaddleSharp官方说明需要安装驱动如下 CUDA 和 cuDNN 和 Tensor ...