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 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법

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




예전에도 이야기했지만,

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

데스크톱 응용 프로그램에서도 UWP 앱에 제공되는 타입들을 사용할 수 있습니다. 이번에는 그중에서 TTS(Text-to-speech) 기능을 제공하는 SpeechSynthesizer 타입을 알아보겠습니다.

SpeechSynthesizer Class (Namespace: Windows.Media.SpeechSynthesis)
; https://learn.microsoft.com/en-us/uwp/api/windows.media.speechsynthesis.speechsynthesizer

* 최소 요구 사항: Windows 10(v10.0.10240.0)

이 타입을 사용하는 예제 코드는 마이크로소프트의 UWP 앱 샘플에서,

Speech recognition and synthesis sample
; https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/SpeechRecognitionAndSynthesis

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

.\Samples\SpeechRecognitionAndSynthesis\cs\SpeechAndTTS.sln 솔루션 파일을 열어 테스트할 수 있습니다.




자, 그럼 사용해 볼까요? ^^

우선 SpeechSynthesizer 정의를 비롯해 UWP의 기본 타입들을 담고 있는 라이브러리를 먼저 참조해야 합니다. 원래 UWP 용으로는 다음과 같은 식의 경로에 있는 Windows.Foundation.UniversalApiContract.winmd 파일을 참조하는데,

C:\Program Files (x86)\Windows Kits\10\References\10.0.16299.0\Windows.Foundation.UniversalApiContract\5.0.0.0\Windows.Foundation.UniversalApiContract.winmd

데스크톱 응용 프로그램은 저 파일을 참조해서는 안되고 대신 다음의 파일 2개를 참조합니다.

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

그럼 소스 코드에서 다음과 같이 SpeechSynthesizer 클래스를 생성하고, 텍스트가 음성으로 바뀌어 출력될 Stream을 얻을 수 있습니다.

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Windows.ApplicationModel.Resources.Core;
using Windows.Media.SpeechSynthesis;

namespace Listener10
{
    public partial class MainWindow : Window
    {
        private SpeechSynthesizer synthesizer = new SpeechSynthesizer();

        public MainWindow()
        {
            InitializeComponent();

            Speak("test is good");
        }

        private async void Speak(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
                }
                catch (Exception e1)
                {
                    System.Diagnostics.Trace.WriteLine(e1.ToString());
                }
            }
        }
    }
}

문제는 여기서부터입니다. 음성이 출력될 synthesisStream을 재생해야 하는데 UWP 앱 예제에서는 이를 위해 (Windows.UI.Xaml.Controls.)MediaPlayerElement 타입을 사용합니다. 그래서 UWP 앱에서와 같이 WPF의 xaml에서 이를 추가하면,

<Grid>
    <MediaPlayerElement x:Name="media"/>
</Grid>

오류 선이 그어지면서 다음과 같은 메시지를 볼 수 있습니다.

MediaPlayerElement is not supported in a Windows Presentation Foundation (WPF) project.

또는 웹 상에서 검색하면 (Windows.UI.Xaml.Controls.)MediaElement 타입을 사용하는 예제를 볼 수 있는데,

<Grid>
    <MediaElement x:Name="media"/>
</Grid>

mediaElement.SetSource(stream, synthesisStream.ContentType);
mediaElement.Play();

역시 WPF에서는 사용할 수 없습니다. 문제는 UWP 앱의 컨트롤들이 WPF 구조와는 맞지 않기 때문인데 이러한 제약은 UI 컨트롤이 아니면 해당하지 않습니다. 따라서 (Windows.Media.Playback.)MediaPlayer 타입을 이용해 다음과 같이 직접 음성 출력을 해야 합니다.

Windows.Media.Playback.MediaPlayer mp = new Windows.Media.Playback.MediaPlayer();
mp.SetStreamSource(synthesisStream);
mp.Play();

또는 (System.Media.)SoundPlayer 타입을 이용해서도 가능합니다.

System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
sp.Stream = = synthesisStream.AsStream();
sp.Play();




참고로 SSML 구문을 사용하면 보다 더 세밀한 음성 제어가 가능합니다. "Windows-universal-samples/Samples/SpeechRecognitionAndSynthesis/cs/" 예제에 보면 다음과 같은 SSML 텍스트가 리소스로 포함되어 있는데,

<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' 
                             xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
                             xsi:schemaLocation='http://www.w3.org/2001/10/synthesis  http://www.w3.org/TR/speech-synthesis/synthesis.xsd' 
                             xml:lang='en-US'>

<mark name='phonetic'/>This is an example of a phonetic pronunciation:
<phoneme alphabet='x-microsoft-ups' ph='S1 W AA T . CH AX . M AX . S2 K AA L . IH T'> whatchamacallit </phoneme>.

<mark name='date'/>This is an example of a date:
<say-as interpret-as='date' format='mdy'> 04/30/2013 </say-as>.

<mark name='number'/>This is an example of an ordinal number:
<say-as interpret-as='ordinal'> 4 </say-as>.
<mark name='end'/>
</speak>

보는 바와 같이 발음 기호, 날짜, 숫자를 인식하도록 출력을 제어할 수 있습니다. 이를 위해 SynthesizeTextToStreamAsync가 아닌 SynthesizeSsmlToStreamAsync 메서드를 이용해 출력해야 합니다.

SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);

Windows.Media.Playback.MediaPlayer mp = new Windows.Media.Playback.MediaPlayer();
mp.SetStreamSource(synthesisStream);
mp.Play();

정리해 보면, 다음의 코드는 첨부 파일에 포함된 예제 프로젝트의 xaml, xaml.cs 내용입니다.

<Window x:Class="Listener10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Listener10"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="voiceList">
        </ListBox>
    </Grid>
</Window>

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Windows.Media.SpeechSynthesis;

namespace Listener10
{
    public partial class MainWindow : Window
    {
        private SpeechSynthesizer _synthesizer = new SpeechSynthesizer();

        public MainWindow()
        {
            InitializeComponent();

            InitializeListboxVoiceChooser();

            Speak();
        }

        private async void Speak()
        {
            string text = "test is good";
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    SpeechSynthesisStream synthesisStream = await _synthesizer.SynthesizeTextToStreamAsync(text);
                    // SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeSsmlToStreamAsync(Listener10.Properties.Resources.TTSText);

                    //Windows.Media.Playback.MediaPlayer mp = new Windows.Media.Playback.MediaPlayer();
                    //mp.SetStreamSource(synthesisStream);
                    //mp.Play();

                    System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
                    sp.Stream = synthesisStream.AsStream();
                    sp.Play();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.WriteLine(e.ToString());
                }
            }
        }

        private void InitializeListboxVoiceChooser()
        {
            var voices = SpeechSynthesizer.AllVoices;

            VoiceInformation currentVoice = _synthesizer.Voice;

            foreach (VoiceInformation voice in voices.OrderBy(p => p.Language))
            {
                ListBoxItem item = new ListBoxItem();
                item.Content = voice.DisplayName + " (Language: " + voice.Language + ")";
                voiceList.Items.Add(item);

                if (currentVoice.Id == voice.Id)
                {
                    item.IsSelected = true;
                    voiceList.SelectedItem = item;
                }
            }
        }
    }
}




그럼 오류 유형을 한번 알아볼까요? ^^

(Windows.UI.Xaml.Controls.)MediaElement나 (Windows.UI.Xaml.Controls.)MediaPlayerElement가 .xaml 파일에서 생성할 수 없기 때문에 .xaml.cs에서 new를 이용해 생성하려고 시도하면 다음과 같은 예외가 발생합니다.

System.Windows.Controls.MediaElement me = new System.Windows.Controls.MediaElement();

/*

{"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"}

*/

분명히 UI 스레드인데도 불구하고 저런 오류가 발생합니다. 실제로 UWP의 Dispatcher 역시 WPF에서 사용하게 되면 0x8000000e 예외가 발생합니다.

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    // Your UI update code goes here!
});

{"A method was called at an unexpected time.\r\n\r\nCould not create a new view because the main window has not yet been created"}

왜냐하면 WPF의 UI 엔진이 UWP의 UI 엔진과 호환하지 않기 때문입니다. 이 외에도 UWP에서만 가능한 구성 요소들은 WPF에서 사용할 수 없습니다. 안 그러면 다음과 같은 식의 예외가 발생합니다.

ResourceContext context = ResourceContext.GetForCurrentView();

{"Unsupported MRT profile type. (Exception from HRESULT: 0x80073B20)"}




MediaElement 타입의 경우 WPF에서 System.Windows.Controls 네임스페이스를 통해 제공되긴 합니다. 하지만 UWP의 것과 완전히 다르기 때문에 UWP 예제에 나온 식으로 사용할 수 없습니다. 가령 UWP의 Windows.UI.Xaml.Controls.MediaElement의 경우 IRandomAccessStream을 인자로 받는 SetSource 메서드가 있지만 WPF에서 제공하는 System.Windows.Controls.MediaElement에는 Uri 타입만을 받는 Source 속성이 있을 뿐입니다.




참고로, Windows 10 미만의 버전이라면 System.Speech.Synthesis.SpeechSynthesizer를 사용하는 것도 방법입니다.

C#으로 만드는 음성인식/TTS 프로그램
; https://www.sysnet.pe.kr/2/0/1228





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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2017-12-20 04시02분
음성인식/TTS를 위해서는 환경 설정이 필요합니다.

윈도우 10 - TTS 및 음성 인식을 위한 환경 설정
; http://www.sysnet.pe.kr/2/0/11413

(2017-12-21 기준으로 아직 한글은 음성 인식을 지원하지 않습니다.)
정성태

... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13169정성태11/23/20225593Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224874제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20224904.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224633개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224540개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225458개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225380개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226457.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225699.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225627.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228798.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225111오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225758.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226668.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226186디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225653.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20226926.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225557.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225674C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225711C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225638오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225628오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224756오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225585.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225845오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225695.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...