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

1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13398정성태8/3/20234135스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233641닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233341스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233311개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233254오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233420닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233297오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233368닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233338스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233322개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233511오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233531오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233601Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233816Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233565.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233313개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233356.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233741오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233195스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233208스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233094오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236891오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233282.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20232983스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233110오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234398오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...