C++ WinRT 通过 MediaPlayer::Play() 播放 SpeechSynthesisStream 需要一些等待,不是吗?
我正在尝试使用下面的代码在主线程中通过 MediaPlayer 播放 SpeechSynthesisStream(最小示例):
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();
}
问题是,如果我在调用 Play() 后不阻止线程(如注释的 Sleep() 调用),我听不到声音。阻塞线程有帮助,但显然这不是正确的解决方案,我想知道为什么会发生这种情况以及如何正确实现它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您在播放源之前关闭媒体和源,Play 不是阻塞调用。
您可以将 media.Close() 添加到类的析构函数中,但不应在每次 Play 调用后关闭它。
和源码几乎一样。如果重复调用 media.Source,您可以决定是要将新内容添加到当前流的末尾,还是要关闭上一个流并将媒体源更改为新的媒体源。
如果您想阻塞线程直到媒体完成(即从线程返回之前),您可以订阅 MediaEnded 事件。
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.