- Home /
How can I change the color of the cube with speech recognition ?
How can I change colour of cube with voice/speech. I have sample code with me
1) VoiceController using UnityEngine; using UnityEngine.UI;
public class VoiceController : MonoBehaviour {
AndroidJavaObject activity;
AndroidJavaObject plugin;
public delegate void OnResultRecieved(string result);
public static OnResultRecieved resultRecieved;
private void Start() {
InitPlugin();
}
void InitPlugin() {
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
plugin = new AndroidJavaObject(
"com.example.matthew.plugin.VoiceBridge");
}));
activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
plugin.Call("StartPlugin");
}));
}
/// <summary>
/// gets called via SendMessage from the android plugin GameObject must be called "VoiceController"
/// </summary>
/// <param name="recognizedText">recognizedText.</param>
public void OnVoiceResult(string recognizedText) {
Debug.Log(recognizedText);
resultRecieved?.Invoke(recognizedText);
}
/// <summary>
/// gets called via SendMessage from the android plugin
/// </summary>
/// <param name="error">Error.</param>
public void OnErrorResult(string error) {
Debug.Log(error);
}
public void GetSpeech() {
// Calls the function from the jar file
activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
plugin.Call("StartSpeaking");
}));
}
}
2) VoiceTest using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
[RequireComponent(typeof(VoiceController))] public class VoiceTest : MonoBehaviour {
public Text uiText;
VoiceController voiceController;
public void GetSpeech() {
voiceController.GetSpeech();
}
void Start() {
voiceController = GetComponent<VoiceController>();
}
void OnEnable() {
VoiceController.resultRecieved += OnVoiceResult;
}
void OnDisable() {
VoiceController.resultRecieved -= OnVoiceResult;
}
void OnVoiceResult(string text) {
uiText.text = text;
}
}
Comment
Answer by xxmariofer · Mar 12, 2019 at 12:22 PM
in the onvoiceresult method
void OnVoiceResult(string text) {
if(text == Color.green){ mat.color = Color.green; }//mat is just the material of the gamobject you want to change just assign in the inspector.
uiText.text = text;
}