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분
정성태

... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13095정성태7/7/20226297Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20225985오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20226910.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227840.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226676.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225802오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226291개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225418개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228354스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227787.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227851.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226464개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227027.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226059.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226131.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226758개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224546오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226553.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226889스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225844Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226145.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226346Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226635Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227217스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227035오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229257.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...