Universal Windows Platform – Speaking App

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu locate and select Visual Studio 2017.

vs2017-home

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project

vs2017-new-project

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 7

Then in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Media.SpeechSynthesis;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

public class Library
{
    private const string extension_txt = ".txt";
    private const string extension_wav = ".wav";

    private SpeechSynthesizer synth = new SpeechSynthesizer();

    private async Task<string> OpenAsync()
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker()
            {
                SuggestedStartLocation = PickerLocationId.ComputerFolder
            };
            picker.FileTypeFilter.Add(extension_txt);
            StorageFile open = await picker.PickSingleFileAsync();
            if (open != null)
            {
                return await FileIO.ReadTextAsync(open);
            }
        }
        finally
        {
        }
        return null;
    }

    private async void SaveAsync(string contents)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker()
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                DefaultFileExtension = extension_txt,
                SuggestedFileName = "Document"
            };
            picker.FileTypeChoices.Add("Text File", new List<string>() { extension_txt });
            picker.FileTypeChoices.Add("Wave File", new List<string>() { extension_wav });
            StorageFile save = await picker.PickSaveFileAsync();
            if (save != null)
            {
                if (save.FileType == extension_txt)
                {
                    await FileIO.WriteTextAsync(save, contents);
                }
                else if (save.FileType == extension_wav)
                {
                    using (SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(contents))
                    {
                        using (DataReader reader = new DataReader(stream))
                        {
                            await reader.LoadAsync((uint)stream.Size);
                            IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
                            await FileIO.WriteBufferAsync(save, buffer);
                        }
                    }
                }
            }
        }
        finally
        {
        }
    }

    private async void Speak(string text, MediaElement media)
    {
        try
        {
            if (media.CurrentState == MediaElementState.Playing)
            {
                media.Stop();
            }
            else
            {
                SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
                media.AutoPlay = true;
                media.SetSource(stream, stream.ContentType);
                media.Play();
            }
        }
        finally
        {
        }
    }

    public Dictionary<string, string> Voices()
    {
        Dictionary<string, string> results = new Dictionary<string, string>();
        foreach (VoiceInformation voice in SpeechSynthesizer.AllVoices.OrderBy(o => o.DisplayName))
        {
            results.Add(voice.Id, voice.DisplayName);
        }
        return results;
    }

    public void Voice(string id)
    {
        synth.Voice = SpeechSynthesizer.AllVoices.First(f => f.Id == id);
    }

    public void New(ref TextBox text, ref MediaElement media)
    {
        media.Source = null;
        text.Text = string.Empty;
    }

    public async void Open(TextBox text)
    {
        string content = await OpenAsync();
        if (content != null)
        {
            text.Text = content;
        }
    }

    public void Save(ref TextBox text)
    {
        SaveAsync(text.Text);
    }

    public void Play(ref TextBox text, ref MediaElement media)
    {
        Speak(text.Text, media);
    }
}

Step 8

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<Grid Name="Display" Loaded="Display_Loaded">
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="*"/>
		<RowDefinition Height="Auto"/>
	</Grid.RowDefinitions>
	<CommandBar Grid.Row="2">
		<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
		<AppBarButton Name="Open" Icon="OpenFile" Label="Open" Click="Open_Click"/>
		<AppBarButton Name="Save" Icon="Save" Label="Save" Click="Save_Click"/>
		<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
	</CommandBar>
	<ComboBox Grid.Row="0" Name="Voice" HorizontalAlignment="Stretch" 
		SelectedValuePath="Key" DisplayMemberPath="Value" 
		SelectionChanged="Voice_SelectionChanged"/>
	<TextBox Grid.Row="1" Name="Input" AcceptsReturn="True" TextWrapping="Wrap"/>
	<MediaElement Name="Media" AutoPlay="False"/>
</Grid>

It should appear as such:

xaml-speaking-app

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Display_Loaded(object sender, RoutedEventArgs e)
{
	Voice.ItemsSource = library.Voices();
	Voice.SelectedIndex = 0;
}

private void Voice_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Voice((string)Voice.SelectedValue);
}

private void New_Click(object sender, RoutedEventArgs e)
{
	library.New(ref Input, ref Media);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.Open(Input);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.Save(ref Input);
}

private void Play_Click(object sender, RoutedEventArgs e)
{
	library.Play(ref Input, ref Media);
}

It should then appear as such:

code-speaking-app

Step 13

That completes the Universal Windows Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-debug

Step 14

Once started the Application should then appear

run-speaking-app

Step 15

After the Application has started running you can then select New to reset the TextBox or use Open to set the content to a Text Document or Save contents to a Text Document or Speech to a Wave File and use Play to convert content from text-to-speech – you can choose the Voice to speak with from the ComboBox at the top.

ran-speaking-app

Step 16

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Advertisements

One thought on “Universal Windows Platform – Speaking App

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s