uwp 之语音朗读

xml code

---------------------------------

<Page

    x:Class="MyApp.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:MyApp"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

 

    <StackPanel>

        <TextBox Name="txtInput" Header="请输入文本:"/>

        <Button Content="开始朗读" Click="OnClick" Margin="0,15,0,0"/>

        <MediaElement Name="me" AutoPlay="True" Volume="1.0"/>

    </StackPanel>

</Page>

 

 

C# code

----------------------

  public sealed partial class MainPage : Page

    {

        public MainPage()

        {

            this.InitializeComponent();

 

            this.NavigationCacheMode = NavigationCacheMode.Required;

        }

 

        private async void OnClick(object sender, RoutedEventArgs e)

        {

            if (txtInput.Text.Length == 0) return;

 

            Button b = sender as Button;

            b.IsEnabled = false;

 

            SpeechSynthesizer synthesizer = new SpeechSynthesizer();

            SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync(txtInput.Text);

            // 播放生成的语音

            me.SetSource(stream, stream.ContentType);

 

            b.IsEnabled = true;

        }

    }

 

posted @ 2021-01-02 23:36  MaxBruce  阅读(78)  评论(0编辑  收藏  举报