System.Speech in .NET MAUI

System.speech in .Net MAUI

You can incorporate voice functionality into your .NET MAUI application for WinUI devices using the System.Speech NuGet package.

In this article, I'll show you how to integrate System.Speech with .NET 8 in a .NET MAUI application.

Please note that the System.Speech NuGet package is only compatible with WinUI (Windows) devices.

For example, the Application in this guide will greet the user with a welcome message.

The code for this is provided below.

const int PDefaultRate = 0;

private static bool initHello {get;set;} = false;

/// <summary>
/// Initializes the singleton application object.  This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
    this.InitializeComponent();

    if (!initHello)
    {
        InitTimer();
    }
    
}

private async void InitTimer()
{
    while (Microsoft.Maui.Controls.Application.Current == null)
    {
        await Task.Delay(500);
    }

    Appearing();
}

private void Appearing()
{
    IDispatcherTimer? timer = Microsoft.Maui.Controls.Application.Current?.Dispatcher.CreateTimer();
    if (timer != null)
    {
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (sender, _) =>
        {
            if (sender is IDispatcherTimer tmr)
            {
                tmr.Stop();
                WelCome();
            }
        };
        timer.Start();                        
    }        
}

private void WelCome()
{
    if (initHello) return;

    initHello = true;

    string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split("\\")[1];
    string appName = AppInfo.Name;

    var voice = new System.Speech.Synthesis.SpeechSynthesizer();
    var voices = voice.GetInstalledVoices();
    if (voices != null && voices.Count > 0) voice.SelectVoice(voices[1].VoiceInfo.Name);
    voice.SetOutputToDefaultAudioDevice();
    voice.Rate = PDefaultRate;        
    voice.Speak($"Hello {userName}, welcome to my .NET MAUI {appName} application!");        
}

In the code

  • Line 3: We establish an initializer to avoid repeating the speech.
  • Line 15: A Timer is initialized to delay execution until the Application is fully started, as indicated by the Application.Current not returning null.
  • Line 33: Another Timer is set up for loading the message to the interface asynchronously.
  • Lines 58-63: This segment triggers the speech function. Specifically, in line 60, we select the second voice option, which is typically a female voice.

Additionally, the following code needs to be added to the MainPage.

public MainPage()
{
    InitializeComponent();
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    DevicePlatform? platform = DeviceInfo.Platform;
    if (platform != null && platform == DevicePlatform.WinUI)
    {
        GoodBye();
    }
}

public void GoodBye()
{
    var voice = new System.Speech.Synthesis.SpeechSynthesizer();
    var voices = voice.GetInstalledVoices();
    if (voices != null && voices.Count > 0) voice.SelectVoice(voices[1].VoiceInfo.Name);
    voice.SetOutputToDefaultAudioDevice();
    voice.Rate = 0;
    voice.Speak($"See you later!");
}

In the code, line 10 checks if the Application runs on a Windows platform, and line 12 triggers the GoodBye() function.

This article provided insights on

  • How to implement and use the System.Speech library.
  • Methods to invoke a specific function when the OnDisappearing() event occurs.
  • Techniques to determine whether an application operates on a WinUI device.

Conclusion

Adding speech capability to .NET MAUI apps running on Windows is viable and relatively simple.

This feature enables a variety of interactive and accessible capabilities for Windows-based applications.

Furthermore, this functionality has the potential to be extended to other systems.

If there is a high demand from the community, Microsoft may explore making a System.Speech is available for other OS systems via.NET MAUI.

This advancement would increase the versatility and reach of .NET MAUI apps across multiple platforms.

The source code is attached to this article.

Feel free to test and use it as needed. We appreciate your interest and hope you find it useful.

I'd like to remind you that .NET MAUI is a framework that Progress Telerik collaborated with Microsoft to create.


Similar Articles