C++ WinRT Playback SpeechSynthesisStream via MediaPlayer::Play() requires some waiting, doesn't it?

269 Views Asked by At

I'm trying to playback SpeechSynthesisStream via MediaPlayer in main thread using the code below(minimal example):

void SpeakStream(winrt::Windows::Media::Playback::MediaPlayer& media, winrt::Windows::Media::SpeechSynthesis::SpeechSynthesisStream& sse)
{
    auto source = winrt::Windows::Media::Core::MediaSource::CreateFromStream(sse, sse.ContentType());
    
    media.Source(source);
    media.Play();

    //Sleep(5000);
    
    source.Close();
    media.Close();
}

The problem is that if I do not block thread after calling Play() (like commented Sleep() call), I don't hear sound. Blocking thread helps, but obviously that is not correct solution and I want to know why it happens and how to correctly implement this.

1

There are 1 best solutions below

1
vagoston On

Actually, you close media and source before it could play the source, Play is not a blocking call. You could add media.Close() to the destructor of your class, you should not close that after each Play call. Almost the same with the source. If you call media.Source repeatedly, you can decide if you want to add the new content to the end of the current strem, or you want to close the previous stream and change the media source to the new one. If you want to block the thread until media is finished i.e. before returning from a thread, you can subscribe to the MediaEnded event.