Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제
; https://www.sysnet.pe.kr/2/0/11106

.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET Framework: 715. C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

.NET Framework: 722. C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11420

.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11799

.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법
; https://www.sysnet.pe.kr/2/0/12001

.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출
; https://www.sysnet.pe.kr/2/0/12470

닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
; https://www.sysnet.pe.kr/2/0/13438




C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법

(업데이트: 2023-03-30) 이 글에 대한 질문은 더 이상 받지 않습니다. (하시다 보면, 제가 왜 이 기술에 대해 흥미를 못 느끼는 지 아시게 될 것입니다. ^^ SpeechRecognitionEngine에 특별한 업데이트가 없는 한 다루지 않을 것입니다.)




TTS(Text-to-Speech)를 다뤘으니,

C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

당연히 이제 음성인식을 봐야 할 차례입니다. ^^ 새로운 (Windows.Media.SpeechRecognition.)SpeechRecognizer 역시 Windows 10부터 지원하는데,

Windows.Media.SpeechRecognition.SpeechRecognizer
; https://learn.microsoft.com/en-us/uwp/api/windows.media.speechrecognition.speechrecognizer

* 최소 사양: Windows 10 (introduced v10.0.10240.0) 

Windows Phone 예제 코드로 사용법이 잘 공개돼 있습니다.

Windows-universal-samples/Samples/SpeechRecognitionAndSynthesis/
; https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/SpeechRecognitionAndSynthesis

예제 프로젝트의 xaml 파일명을 보면 대충 어떤 식의 음성 인식이 가능한지 짐작할 수 있습니다.

  • Scenario_ContinuousDictation.xaml
  • Scenario_ContinuousRecognitionListGrammar.xaml
  • Scenario_ContinuousRecognitionSRGSGrammar.xaml
  • Scenario_ListConstraint.xaml
  • Scenario_PauseAsync.xaml
  • Scenario_PredefinedDictationGrammar.xaml
  • Scenario_PredefinedWebSearchGrammar.xaml
  • Scenario_SRGSConstraint.xaml




방법은 역시 지난번과 별반 다르지 않습니다. 우선, UWP 타입을 사용하기 위한 참조를 추가하고,

C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

음성 인식을 위한 객체를 생성하면 됩니다.

_speechRecognizer = new SpeechRecognizer(speechLanguage);

그다음 음성 인식을 위한 규칙을 적용하고, (아래의 예에서는 Free Dictation으로 음성 인식을 합니다.)

var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation");
_speechRecognizer.Constraints.Add(dictationConstraint);
SpeechRecognitionCompilationResult compilationResult = await _speechRecognizer.CompileConstraintsAsync();

이후, 음성 인식을 시작합니다.

SpeechRecognitionResult speechRecognitionResult = await _speechRecognizer.RecognizeAsync();

if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
    string txt = speechRecognitionResult.Text; // 사용자가 말한 문장
}

그다지 어려운 면이 없습니다. ^^




사실 Free Dictation 형식은 그다지 쓸만한 경우가 거의 없습니다. 대신, 문맥에 따라 정해진 문구를 인식하도록 만드는 것이 더 유용합니다. 가령, "Jarvis, turn off the PC"라는 문장을 인식하도록 만들고, 그 문장이 인식되었으면 TTS로 "Are you sure?"라고 되물은 후 "Yes", "No"를 인식하는 식으로 처리하는 것이 좋습니다.

문장 인식이 될 후보군을 지정하는 방법은 SpeechRecognizer.Constraints에 적절한 단어를 Add하면 됩니다. 비교를 위해 Free Dictation은 Constraints에 다음과 같이 포함했지만,

var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation");
_speechRecognizer.Constraints.Add(dictationConstraint);

문장 인식 후보군은 이렇게 제약 사항으로 추가하면 됩니다.

string[] list = new[] { "Jarvis! turn off the PC", "Jarvis! open explorer" };
_speechRecognizer.Constraints.Add(new SpeechRecognitionListConstraint(list));
await _speechRecognizer.CompileConstraintsAsync();

위의 문장으로 음성인식을 시작하고 인식이 되면,

SpeechRecognitionResult speechRecognitionResult = await _speechRecognizer.RecognizeAsync();

if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
    string txt = speechRecognitionResult.Text;    
}

기존 제약 사항을 제거하고 새로운 제약 사항으로 채우면 됩니다.

string[] list = new[] { "Yes", "No" };

_speechRecognizer.Constraints.Clear();
_speechRecognizer.Constraints.Add(new SpeechRecognitionListConstraint(list));
await _speechRecognizer.CompileConstraintsAsync();

간단합니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




이하 오류 정리입니다.

다음과 같은 오류가 발생한다면?

{"'System.__ComObject' does not contain a definition for 'GetAwaiter'"}
   at CallSite.Target(Closure , CallSite , ComObject )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at Listener10.MainWindow.<InitSpeechRecognizer>d__3.MoveNext() in F:\Listener10\MainWindow.xaml.cs:line 59

Task가 아닌 객체를 await 했을 때 발생하는 것입니다.

dynamic result = GetTest();
await result;




데스크톱 형식의 응용 프로그램에서 IAsyncOperation을 사용하면,

Windows.Foundation.IAsyncOperation<SpeechRecognitionResult> result = _speechRecognizer.RecognizeAsync();

이런 오류가 발생합니다.

Error CS0433 The type 'IAsyncOperation<TResult>' exists in both 'Windows.Foundation.FoundationContract, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime' and 'Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'

오류 메시지에 따라 Windows.Foundation.IAsyncOperation<TResult> 타입이 Windows.winmd에도 있고, Windows.Foundation.FoundationContract.winmd에도 있기 때문입니다. 이런 경우에는 TResult 타입을 곧바로 반환받도록 다음과 같이 처리를 하면 됩니다.

SpeechRecognitionResult speechRecognitionResult = await _speechRecognizer.RecognizeAsync();




다음의 코드를 호출 시,

_speechRecognizer.RecognizeWithUIAsync(); 

이런 예외가 발생할 수 있습니다.

The text associated with this error code could not be found.
The speech privacy policy was not accepted prior to attempting a speech recognition.

검색해 보면,

Exception: The speech privacy policy was not accepted prior to attempting a speech recognition
; https://stackoverflow.com/questions/42391526/exception-the-speech-privacy-policy-was-not-accepted-prior-to-attempting-a-spee

"Settings" / "Time & Language" / "Speech"에서 "Related settings" 범주의 "Speech, inking, & typing privacy settings" 링크를 눌러 나오는 다음의 화면에서,

asr_rec_error_1.png

"Turn on speech services and typing suggestions" 버튼을 눌러 "Turn on"을 설정하면 됩니다.




빌드 시 다음과 같은 오류가 발생한다면?

1>------ Rebuild All started: Project: SpeechAndTTS, Configuration: Debug ARM ------
1>E:\git_clone\uwp_samples\Samples\SpeechRecognitionAndSynthesis\cs\SpeechAndTTS.csproj : XamlCompiler error WMC1006: Cannot resolve Assembly or Windows Metadata file 'Type universe cannot resolve assembly: System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.'
1>CSC : error CS2001: Source file 'E:\git_clone\uwp_samples\Samples\SpeechRecognitionAndSynthesis\cs\obj\ARM\Debug\App.g.i.cs' could not be found.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

당황하지 마시고 ^^ 솔루션 탐색기의 솔루션 이름을 마우스 우 클릭해, "Restore NuGet Packages" 메뉴를 실행한 후 다시 빌드하면 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/30/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2017-12-31 07시05분
[학생] 혹시 한국어 인식도 지원하나요? 문화 코드를 보니 한국어는 없는 거 같던데...
[guest]
2017-12-31 12시34분
한국어는 미지원으로 알고 있습니다. 아마 cortana 나올 때까지 기다려야 할 듯 싶은데 계속 미뤄진다는 소식만 들리고 있군요. ^^;
정성태
2023-06-10 03시04분
정성태

... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12470정성태12/30/202010042.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [1]파일 다운로드1
12469정성태12/30/202013635.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스 [1]파일 다운로드1
12468정성태12/30/202010239Windows: 186. CMD Shell의 "Defaults"와 "Properties"에서 폰트 정보가 다른 문제 [1]
12467정성태12/29/202010151.NET Framework: 989. HttpContextAccessor를 통해 이해하는 AsyncLocal<T> [1]파일 다운로드1
12466정성태12/29/20208164.NET Framework: 988. C# - 지연 실행이 꼭 필요한 상황이 아니라면 singleton 패턴에서 DCLP보다는 static 초기화를 권장파일 다운로드1
12465정성태12/29/202011281.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
12464정성태12/29/202010127.NET Framework: 986. pptfont.exe - PPT 파일에 숨겨진 폰트 설정을 일괄 삭제
12463정성태12/29/20209178개발 환경 구성: 520. RDP(mstsc.exe)의 다중 모니터 옵션 /multimon, /span
12462정성태12/27/202010782디버깅 기술: 177. windbg - (ASP.NET 환경에서 유용한) netext 확장
12461정성태12/21/202011592.NET Framework: 985. .NET 코드 리뷰 팁 [3]
12460정성태12/18/20209288기타: 78. 도서 소개 - C#으로 배우는 암호학
12459정성태12/16/20209710Linux: 35. C# - 리눅스 환경에서 클라이언트 소켓의 ephemeral port 재사용파일 다운로드1
12458정성태12/16/20209221오류 유형: 694. C# - Task.Start 메서드 호출 시 "System.InvalidOperationException: 'Start may not be called on a task that has completed.'" 예외 발생 [1]
12457정성태12/15/20208778Windows: 185. C# - Windows 10/2019부터 추가된 SIO_TCP_INFO파일 다운로드1
12456정성태12/15/20209040VS.NET IDE: 156. Visual Studio - "Migrate packages.config to PackageReference"
12455정성태12/15/20208545오류 유형: 693. DLL 로딩 시 0x800704ec - This Program is Blocked by Group Policy
12454정성태12/15/20209133Windows: 184. Windows - AppLocker의 "DLL Rules"를 이용해 임의 경로에 설치한 DLL의 로딩을 막는 방법 [1]
12453정성태12/14/202010116.NET Framework: 984. C# - bool / BOOL / VARIANT_BOOL에 대한 Interop [1]파일 다운로드1
12452정성태12/14/202010268Windows: 183. 설정은 가능하지만 구할 수는 없는 TcpTimedWaitDelay 값
12451정성태12/14/20209463Windows: 182. WMI Namespace를 열거하고, 그 안에 정의된 클래스를 열거하는 방법 [5]
12450정성태12/13/202010172.NET Framework: 983. C# - TIME_WAIT과 ephemeral port 재사용파일 다운로드1
12449정성태12/11/202010587.NET Framework: 982. C# - HttpClient에서의 ephemeral port 재사용 [2]파일 다운로드1
12448정성태12/11/202012208.NET Framework: 981. C# - HttpWebRequest, WebClient와 ephemeral port 재사용파일 다운로드1
12447정성태12/10/202010340.NET Framework: 980. C# - CopyFileEx API 사용 예제 코드파일 다운로드1
12446정성태12/10/202010953.NET Framework: 979. C# - CoCreateInstanceEx 사용 예제 코드파일 다운로드1
12445정성태12/8/20208418오류 유형: 692. C# Marshal.PtrToStructure - The structure must not be a value class.파일 다운로드1
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...