question

elvisxia avatar image
elvisxia asked ·

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

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://docs.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?

windows-uwpwindows-uwp-runtime
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
RoyLi-MSFT answered ·

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://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/.

Thanks



Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.