LoginSignup
3
2

More than 1 year has passed since last update.

Unityで音声認識(Speech to text)

Posted at

こんにちは。大学生のKuniと申します。
大学でちょっとUnityの音声認識を使う機会がありまして、その備忘録としてこの記事を書いています。

やったこと

Unityの機能を使って話した言葉を文章として書き起こす(Speech To Text)ということをしました。
使ったものとしてUnityEngine内に含まれるWindows.Speech.DictationRecognizerというものを使いました。

環境

Windows 11
Unity 2021.3.22f1
Visual Studio 2019

始める前に

Windowsの設定 → プライバシーとセキュリティ → 音声認識の中にある、オンライン音声認識の設定をONにしてください。
これをONにしないとエラーが出て動作をしません。

コード

SpeechToText
using UnityEngine;
using UnityEngine.Windows.Speech;

public class SpeechToText : MonoBehaviour
{
	DictationRecognizer dictationRecognizer;

	private void Start()
	{
		dictationRecognizer = new DictationRecognizer();

		dictationRecognizer.DictationResult += DictationRecResult;
		dictationRecognizer.DictationError += DictationRecError;		
	}

	private void Update()
	{
		if (Input.GetKeyDown(KeyCode.Space) && dictationRecognizer.Status == SpeechSystemStatus.Stopped)
		{
			dictationRecognizer.Start();
			Debug.Log("音声認識開始");
		}
		if(Input.GetKeyUp(KeyCode.Space) && dictationRecognizer.Status == SpeechSystemStatus.Running)
		{
			dictationRecognizer.Stop();
			Debug.Log("音声認識停止");
		}
	}

    //音声が認識されたときに発生するイベント
	private void DictationRecResult(string text, ConfidenceLevel confidence)
	{
		Debug.Log($"認識した音声: {text}");
	}

    //何かしらのエラーが起きた時に発生するイベント
	private void DictationRecError(string error, int hresult)
	{
		Debug.Log($"エラー:{error}, {hresult}");
	}

    //オブジェクトが破壊されるときに破棄する
	private void OnDestroy()
	{
		dictationRecognizer.Stop();
		dictationRecognizer.Dispose();
	}
}

このコードでは、Spaceキーが押されている間は音声認識がされるようにしてあります。
離した時には、音声認識は止まります。

まとめ

今回はUnityの音声認識を使用して実装を行いました。ただ精度が荒いときもあるので、気になる方は他のライブラリを探してみてください。
私の環境だと日本語は反応するのですが、なぜか英語は反応しませんでした。この点について詳しい方がいましたらコメント等いただけると嬉しいです。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2