首页 > 技术文章 > 小梦windows phone 8.1开发:语音朗读

xdoudou 2014-08-29 16:38 原文

使用SpeechSynthesizer类可以实现文本朗读功能,位于 Windows.Media.SpeechSynthesis命名空间。有了它我们就可以实现有声小说了,是不是很爽。下面给出一个将文本块的内容朗读出来的例子,记得在应用的功能里要勾选 麦克风。

关于SpeechSynthesizer类的详细说明请参考:

http://technet.microsoft.com/zh-cn/sysinternals/system.speech.synthesis.speechsynthesizer(v=vs.95).aspx

mainpage页面布局如下:

<Grid>
<StackPanel >
<TextBox x:Name=”txtToSay” Width=”300″ Height=”90″ Margin=”0 2 0 12″ TextWrapping=”Wrap”/>
<Button Content=”开始朗读” HorizontalAlignment=”Center” Click=”OnClick”/>
</StackPanel>
<MediaElement x:Name=”mdPlayer” Width=”0″ Height=”0″ AutoPlay=”True”/>
</Grid>

后台代码如下:

private async void OnClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(txtToSay.Text)) return;
SpeechSynthesizer speech = new SpeechSynthesizer();//实例化对象
// 朗读文本
SpeechSynthesisStream stream = await speech.SynthesizeTextToStreamAsync(txtToSay.Text);//将文本框的内容转化为语音流输出
if (stream != null)
{
this.mdPlayer.SetSource(stream, stream.ContentType);//将语音流设为MediaElement的源。
}

}

关于MediaElement的SetSource方法请查看:http://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/br244338.aspx

推荐阅读