Use Baidu Chinese speech recognition function in unity

Source: Internet
Author: User

Here is the API class
Asr.cs

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine;/// <summary>///JSON data for user resolution token/// </summary>classtokenresponse{ Public stringAccess_token =NULL;} Public classasr{ Public stringSecretkey {Get;Private Set; }  Public stringAPIKey {Get;Private Set; }  Public stringToken {Get;Private Set; }  PublicASR (stringApiKey,stringSecretkey) {APIKey=ApiKey; Secretkey=Secretkey; }     PublicIEnumerator Getaccesstoken () {varURI =string. Format ("Https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_ Secret={1}", APIKey, Secretkey); varwww =NewWWW (URI); yield returnwww; if(string. IsNullOrEmpty (Www.error)) {varresult = Jsonutility.fromjson<tokenresponse>(Www.text); Token=Result.access_token; Debug.Log ("Get Access_token successfully"); }        Else{debug.logerror (www.error); }    }     PublicIEnumerator recognize (byte[] Data, action<string>callback) {        varURI =string. Format ("Http://vop.baidu.com/server_api?lan=zh&cuid={0}&token={1}", Systeminfo.deviceuniqueidentifier, Token); varheaders =Newdictionary<string,string> {{"Content-type","audio/pcm;rate=16000" } }; varwww =NewWWW (URI, data, headers); yield returnwww; if(string.            IsNullOrEmpty (Www.error)) {Debug.Log (www.text);        Callback (Www.text); }        ElseDebug.logerror (Www.error); }    /// <summary>    ///Convert Unity's AudioClip data to PCM format 16bit data/// </summary>    /// <param name= "clip" ></param>    /// <returns></returns>     Public Static byte[] ConvertAudioClipToPCM16 (audioclip clip) {varSamples =New float[Clip.samples *Clip.channels]; Clip. GetData (samples,0); varSamples_int16 =New  Short[Samples.        Length];  for(varindex =0; Index < samples. Length; index++)        {            varf =Samples[index]; Samples_int16[index]= ( Short) (f * Short.        MaxValue); }        varByteArray =New byte[Samples_int16. Length *2]; Buffer.blockcopy (Samples_int16,0, ByteArray,0, bytearray.length); returnByteArray; }}

Here is the test class

Main.cs

usingUnityengine;usingSystem.Collections;usingUnityengine.ui; Public classMain:monobehaviour { Public stringAPIKey ="";  Public stringSecretkey ="";  PublicButton Startbutton;  PublicButton Stopbutton;  PublicText DescriptionText; PrivateAudioClip _cliprecord =NewAudioClip (); PrivateASR _asr; voidStart () {_asr=NewASR (APIKey, Secretkey); Startcoroutine (_ASR.        Getaccesstoken ()); StartButton.gameObject.SetActive (true); StopButton.gameObject.SetActive (false); Descriptiontext.text="";        StartButton.onClick.AddListener (Onclickstartbutton);    StopButton.onClick.AddListener (Onclickstopbutton); }    Private voidOnclickstartbutton () {StartButton.gameObject.SetActive (false); StopButton.gameObject.SetActive (true); Descriptiontext.text="Listening ..."; _cliprecord= Microphone.start (NULL,false, -,16000); }    Private voidOnclickstopbutton () {StartButton.gameObject.SetActive (false); StopButton.gameObject.SetActive (false); Descriptiontext.text="Recognizing ..."; Microphone.end (NULL); Debug.Log ("End Record"); vardata =asr.convertaudiocliptopcm16 (_cliprecord); Startcoroutine (_ASR. Recognize (data, S={Descriptiontext.text=s; StartButton.gameObject.SetActive (true);    })); }}

Resources originate from Guanl Manic's Technology Park

Http://blog.csdn.net/zhenghongzhi6/article/details/78688571#comments

Use Baidu Chinese speech recognition function in unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.