using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using iFlytekSpeechRecognizer;
using System;
using UnityEngine.UI;

public class SpeechRecognizer : MonoBehaviour
{
    public AudioSource _audio;
    public Text text;

    private int frequency = 16000;//采样率
    private const string app_id = "appid = 5940ac5d";
    private const string session_begin_params = "sub = iat, domain = iat, language = zh_cn, accent = mandarin, sample_rate = 16000, result_type = plain, result_encoding = utf-8";
    // Start is called before the first frame update
    void Start()
    {
        iFlytek.InitiFlytek(app_id, session_begin_params);
        iFlytek.RecognizerResult += Result;
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void StartSpeechRecording()
    {
        _audio.Stop();//停止上一个音频的播放
        _audio.clip = Microphone.Start(null, false, 5, frequency);//开始录制音频,3秒
        while (Microphone.GetPosition(null) <= 0) { Debug.Log("null"); }//防止音频播放出错
    }
    public void StopSpeechRecording()
    {
        if (Microphone.IsRecording(null)) { Microphone.End(null); }//如果麦克没有在录制音频
        Debug.Log("开始播放音频");
        //_audio.Play();
        // audio.Stop();//停止播放音频
        Debug.Log("停止录音");
        byte[] AudioData = Float2Byte();
        //调用语音识别函数
        Debug.Log("开始语音识别");
        iFlytek.StartRecording(AudioData);
    }
    public void Result(string result)
    {
        Debug.Log(result);
        text.text = result;
    }

    private void OnApplicationQuit()
    {
        iFlytek.QuitiFlytek();
    }

    //将clip中的float音频数据存储到byte数组中
    public byte[] Float2Byte()
    {
        if (_audio.clip == null)
        {
            Debug.Log("clip is null!");
            return null;
        }
        float[] samples = new float[_audio.clip.samples];

        _audio.clip.GetData(samples, 0);

        short[] intData = new short[samples.Length];
        //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

        byte[] bytesData = new byte[samples.Length * 2];
        //bytesData array is twice the size of
        //dataSource array because a float converted in Int16 is 2 bytes.

        int rescaleFactor = 32767; //to convert float to Int16

        for (int i = 0; i < samples.Length; i++)
        {
            intData[i] = (short)(samples[i] * rescaleFactor);
            byte[] byteArr = new byte[2];
            byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }
        return bytesData;
    }
}

工程链接



更多推荐