LoginSignup
1
0

C#で音声認識

Last updated at Posted at 2024-04-29

環境

Windows 11 Pro (64bit)
Visual Studio Community 2022

C# 5

dev.bat
@echo off
path %path%;C:\Windows\Microsoft.NET\Framework64\v4.0.30319
prompt $e[33m$p$g$e[m
cmd
recog.cs
using System;
using System.Speech.Recognition;

class Program {
	static void Main() {
		using (var rec = new SpeechRecognitionEngine()) {
			rec.LoadGrammar(new DictationGrammar());
			rec.SpeechRecognized += (sender, e) => {
				Console.WriteLine("> " + e.Result.Text);
			};
			rec.SetInputToDefaultAudioDevice();
			rec.RecognizeAsync(RecognizeMode.Multiple);

			Console.ReadLine();
		}
	}
}

csc /r:"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Speech\v4.0_4.0.0.0__31bf3856ad364e35\System.Speech.dll" recog.cs

でコンパイル。

Add-Type -AssemblyName System.Speech
([AppDomain]::CurrentDomain).GetAssemblies()

System.Speech.dllのpathはPowerShellで確認できる。

Visual Studio C#

適当なプロジェクト名のディレクトリを用意する。
例:C:\Projects\.NET\Recog

dotnet new console

というコマンドを実行するとRecog.csproj Program.csが作られる。

Program.cs
using System.Speech.Recognition;

using var rec = new SpeechRecognitionEngine();
rec.LoadGrammar(new DictationGrammar());
rec.SpeechRecognized += (sender, e) => {
	Console.WriteLine("> " + e.Result.Text);
};
rec.SetInputToDefaultAudioDevice();
rec.RecognizeAsync(RecognizeMode.Multiple);

Console.ReadLine();
dotnet add package System.Speech

で参照を追加する。

dotnet build

でビルド。

Recog.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

warning CA1416: この呼び出しサイトはすべてのプラットフォームで到達可能です。
という警告にはTargetFrameworkをnet8.0-windowsとする。

bin\Debug\net8.0-windows\Recog.exe

で実行。

1
0
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
1
0