语音识别:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Windows.Speech;//引入命名空间 利用
///
/// 语音识别(主要是别关键字)
///
public class speechKey : MonoBehaviour
{
// 短语识别器
private PhraseRecognizer m_PhraseRecognizer;
// 关键字
public string[] keywords = { “你好”, “开始”,“停止” };
// 可信度
public ConfidenceLevel m_confidenceLevel = ConfidenceLevel.Medium;
/// <summary>
/// 显示的文字
/// </summary>
private Text ShowText;
// Use this for initialization
void Start()
{
ShowText = GameObject.Find("ShowText").GetComponent<Text>();
if (m_PhraseRecognizer == null)
{
//创建一个识别器
m_PhraseRecognizer = new KeywordRecognizer(keywords, m_confidenceLevel);
//通过注册监听的方法
m_PhraseRecognizer.OnPhraseRecognized += M_PhraseRecognizer_OnPhraseRecognized;
//开启识别器
m_PhraseRecognizer.Start();
Debug.Log("创建识别器成功");
}
}
/// <summary>
/// 当识别到关键字时,会调用这个方法
/// </summary>
/// <param name="args"></param>
private void M_PhraseRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
SpeechRecognition();
ShowText.text = "识别内容:" + args.text;
print(args.text);
}
private void OnDestroy()
{
//判断场景中是否存在语音识别器,如果有,释放
if (m_PhraseRecognizer != null)
{
//用完应该释放,否则会带来额外的开销
m_PhraseRecognizer.Dispose();
}
}
// Update is called once per frame
void Update()
{
}
/// <summary>
/// 识别到语音的操作
/// </summary>
void SpeechRecognition()
{
}
}
可视化:
using UnityEngine;
using UnityEngine.UI;
///
/// 语音识别音频可视化
///
public class UseMicrophone : MonoBehaviour
{
public GameObject[] obj;
public static float volume;
private AudioClip micRecord;
string device;
void Start()
{
device = Microphone.devices[0];//获取设备麦克风
micRecord = Microphone.Start(device, true, 999, 44100);//44100音频采样率 固定格式
}
void Update()
{
volume = GetMaxVolume();
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
}
/// <summary>
/// 每一振处理那一帧接收的音频文件
/// </summary>
/// <returns></returns>
float GetMaxVolume()
{
float maxVolume = 0f;
//剪切音频
float[] volumeData = new float[128];
int offset = Microphone.GetPosition(device) - 128 + 1;
if (offset < 0)
{
return 0;
}
micRecord.GetData(volumeData, offset);
for (int i = 0; i < 128; i++)
{
float tempMax = volumeData[i];//修改音量的敏感值
//这个if是用来取记录的音频的一部分 和你所加的物体有关
if (i % 4 == 0)
{
int f = i / 4;
obj[f].gameObject.transform.localScale = new Vector3(0.3f, volumeData[i] * 10 + 0.2f, 0.1f);//将可视化的物体和音波相关联
}
}
return maxVolume;
}
}