Unity——科大飞讯语音SDK接入(Windows)
下面有Demo
using iFlytekSpeechRecognizer;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpeechRecognizer : MonoBehaviour
{
private float currentTime = 0;
private float Timeaa = 20;
public AudioSource _audio;
public Text text;
private AudioClip audioClip;
private int frequency = 16000;//采样率
private const string app_id = "appid = 604ef674";//604ef674
//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()
{
if (Input.GetKeyDown(KeyCode.A))
{
StartSpeechRecording();
}
if (Input.GetKeyDown(KeyCode.B))
{
StopSpeechRecording();
}
}
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("开始语音识别");
text.text= iFlytek.StartRecording(AudioData);
}
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;
}
}
链接:https://pan.baidu.com/s/1lzZkmVjm6yuOCA6Y3HlR2g
提取码:e08a
链接失效或者Demo上有什么不懂的,请及时联系我,我会每天看的