Files
plugin-library/Assets/07.RKVoiceCommand/RunTime/VoiceCommandController.cs
2025-04-18 11:18:24 +08:00

93 lines
2.5 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Stary.Evo;
using Rokid.UXR.Module;
using UnityEngine.Android;
public class VoiceCommandController : MonoBehaviour
{
public Dictionary<string, Action> VoiceCommands = new Dictionary<string, Action>();
public bool isInit = false;
void Awake()
{
}
void Start()
{
//if (!Permission.HasUserAuthorizedPermission("android.permission.RECORD_AUDIO")) return;
}
/// <summary>
/// 注册语音指令
/// </summary>
/// <param name="content"></param>
/// <param name="spell"></param>
/// <param name="action"></param>
public void RegisteredVoiceCommand(string content, string spell, Action action)
{
if (!isInit)
{
if (!Permission.HasUserAuthorizedPermission("android.permission.RECORD_AUDIO"))
{
Permission.RequestUserPermission("android.permission.RECORD_AUDIO");
}
ModuleManager.Instance.RegistModule("com.rokid.voicecommand.VoiceCommandHelper", false);
OfflineVoiceModule.Instance.ChangeVoiceCommandLanguage(LANGUAGE.CHINESE);
isInit = true;
}
if (!VoiceCommands.ContainsKey(content))
{
VoiceCommands.Add(content, action);
}
else
{
Debug.LogError($"语音命令 :“'{content}' ”已经注册了!!!");
return;
}
OfflineVoiceModule.Instance.AddInstruct(LANGUAGE.CHINESE, content, spell, this.gameObject.name, "OnReceive");
OfflineVoiceModule.Instance.Commit();
}
/// <summary>
/// 删除语音指令
/// </summary>
/// <param name="content"></param>
public void DeleteVoiceCommand(string content)
{
if (VoiceCommands.ContainsKey(content))
{
VoiceCommands.Remove(content);
}
else
{
Debug.LogWarning($"语音命令 :“'{content}' 不存在!!!");
}
}
/// <summary>
/// 清除所有语音指令
/// </summary>
public void ClearAllVoiceCommand()
{
VoiceCommands.Clear();
OfflineVoiceModule.Instance.ClearAllInstruct();
OfflineVoiceModule.Instance.Commit();
}
void OnReceive(string msg)
{
if (VoiceCommands.TryGetValue(msg, out Action action))
{
action?.Invoke();
}
}
}