[C++/WinRT] How to use SpeechSynthesizer in UWP

Elvis Xia 131 Reputation points Microsoft Employee
2019-10-30T06:45:54.467+00:00

I would like to implement the text to speech feature in my app. I see there are docs on how to do this here: https://learn.microsoft.com/en-us/uwp/api/windows.media.speechsynthesis.speechsynthesizer .

However the example does not compile on a modern winrt app.

// The object for controlling the speech synthesis engine (voice).  
synth = ref new SpeechSynthesizer();  
// The media object for controlling and playing audio.  
media = ref new MediaElement();  
// The string to speak.  
String^ text = "Hello World";  
  
// Generate the audio stream from plain text.  
task speakTask = create_task(synth- >SynthesizeTextToStreamAsync(text));  
speakTask.then([this, text](SpeechSynthesisStream ^speechStream)  
{  
    // Send the stream to the media object.  
    // media === MediaElement XAML object.  
    media->SetSource(speechStream, speechStream->ContentType);  
    media->AutoPlay = true;  
    media->Play();  
});  

How can this example be adapted to work in a modern c++ winrt uwp app?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 31,766 Reputation points Microsoft Vendor
    2019-10-31T01:29:40.937+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    Since calling the SynthesizeTextToStreamAsync() method will start an asynchronous operation, in C++/Winrt you need to write a co_await statement to cooperatively await the result of any function that returns the asynchronous operation. Besides, if the asynchronous method does not communicate a result object or ongoing progress, you need to use IAsyncAction to be the return type. For more information about how to use asynchronous operation in C++/Winrt, you can refer to Concurrency and asynchronous operations with C++/WinRT.

    The correct code will be the following:

    .h  
    private:  
    	  Windows::Foundation::IAsyncAction playsound();  
      
    .cpp  
    Windows::Foundation::IAsyncAction MainPage::playsound() {  
    		synth = Windows::Media::SpeechSynthesis::SpeechSynthesizer();  
      
    		media = Windows::UI::Xaml::Controls::MediaElement();  
      
    		// The string to speak.  
      
    		hstring text = L"Hello World";  
      
    		Windows::Media::SpeechSynthesis::SpeechSynthesisStream speechStream = co_await synth.SynthesizeTextToStreamAsync(text);  
      
    		media.SetSource(speechStream, speechStream.ContentType());  
      
    		media.AutoPlay(true);  
      
    		media.Play();  
    	}  
      
    

    Besides, for more information about how to use the C++/Winrt in UWP, please check the following article:
    https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/.

    Thanks

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful