Xamarin.Forms- Dependency Service (Text To Speech)

Here I am going to explain how we can use the Text to Speech feature in Xamarin.Forms without using any dependency service plugin. It is a beautiful feature and yet simple. If we are not using any plugin, then it will not affect our app size.

Prerequisites

Xamarin.Forms project with PCL approach. 

STEP 1 - Create an Interface class in PCL

Right-click on PCL project ->Add New-> EmptyInterface. Create this Interface class with the name of “ItextToSpeech”.

Create a method inside the class as I am showing in the image.

Xamarin

  1. using System;  
  2. namespace DemoTest.Inerface  
  3. {  
  4.     public interface ItextToSpeeech  
  5.     {  
  6.         void Speak(string text);  
  7.     }  
  8. }  

Now, the interface is created successfully.

STEP 2 - Implement interface method platform-wise

First, we will do it for Android.

Right-click on the .Droid project and add a new class with the name of “TtImplementation”.

Right-click -> Add New-> EmptyClass

Now, we need to do the implementation of that method which we have created in the Interface. For doing this, just follow my screenshot.

Xamarin
  1. [assembly : Dependency(typeof (TtImplementation)]  
  2. namespace DemoTest.Droid  
  3. {  
  4.     public class TtImplementation: java.Lang.Object, ItextToSpeech, TextToSpeech.IOnInitListener  
  5.     {  
  6.         TextToSpeech speaker;  
  7.         string toSpeak;  
  8.         public void Speak(string text)  
  9.         {  
  10.             toSpeak = text;  
  11.             if(speaker==null)  
  12.             {  
  13.                 speaker = new TextToSpeech(Forms.Context, this);  
  14.             }  
  15.             else  
  16.             {  
  17.                 speaker.Speak(toSpeak, QueueMode.Flush, nullnull);  
  18.             }  
  19.         }  
  20.         public void OnInit(OperationResult status)  
  21.         {  
  22.             if(status.Equals(OperationResult.Success))  
  23.             {  
  24.                 speaker.Speak(toSpeak, QueueMode.flush, nullnull);  
  25.             }  
  26.         }  
  27.     }  
  28. }  

Here, implementation of “Speak ” method in .Droid is done.

STEP 3 - FOR iOS

Here also, we will do the same but for iOS. We will create a new class with the name of “TtImplementation” in the iOS project.

For creating this, just right-click on .iOS project -> Add New-> EmptyClass.

For implementing the Speak method which we have created in the interface, just follow the below screenshot.

Xamarin
  1. [assembly : Dependency(typeof (TtImplementation)]  
  2. namespace DemoTest.iOS  
  3. {  
  4.     public class TtImplementation: ItextToSpeech  
  5.     {  
  6.         public TtImplementation()  
  7.         {  
  8.   
  9.         }  
  10.         public void Speak(string text)  
  11.         {  
  12.             var speechSynthesizer = new AVSpeechSynthesizer();  
  13.             var speechUtterance = new AVSpeechUtterance(text)  
  14.             {  
  15.                 Rate= AVSpeechUtterance.MaximumSpeechRate/2,  
  16.                 Voice= AVSpeechSynthesisVoice.FromLanguage("en-Us"),  
  17.                 Volume=0.5f,  
  18.                 PitchMultiplier= 1.0f  
  19.             };  
  20.   
  21.             speechSynthesizer.SpeakUtterance(speechUtterance);  
  22.   
  23.         }  
  24.     }  
  25. }  

All the implementation is done. We have successfully implemented the TextToSpeech feature in our Xamarin.Forms project without using any plugin.

Now, it’s time to check how it is working on both the platforms.

So for testing, I have created a simple application which I am going to show you. So just follow my instructions.

STEP 4 - Create UI for testing

I have created a very simple UI where I have taken 2 Entries,1 Button, and 1 label control.

Go to your Main.xaml file, open it, and write the code as I have written in the following screenshot.

Xamarin
 
 
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DemoTest"
x:Class="DemoTest.DemoTestPage">
<ContentPage.Padding>
<OnPlatform x:TypeArgument="Thickness">
<OnPlatform.Platforms>
<On Platform="iOS" Value="0,20,0,0"/>
<On Platform="Android" Value="0,0,0,0"/>
</OnPlatform.Platforms>
</OnPlatform>
</ContentPage.Padding>
<StackLayout Orientation="Vertical">
<Entry x:Name="valueAentry"
AutomationId="e1"
FontSize="40"/>
<Entry x:Name="valueBentry"
AutomationId="e2"
FontSize="40"/>
<Button Text="ADD"
BackgroundColor="Purple"
TextColor="White"
FontSize="40"
AutomationId="btnAdd"
Clicked="Add_Clicked" />
<Label x:Name="lblresult" FontSize="40" AutomationId="lblRES" />
</StackLayout>
</ContentPage>

You can see that I have created a simple UI.

As I mentioned previously, I have taken a button. So, for that button, I have also created a Click event.

 Open MainPage.xaml.cs file in your PCL project and write the following code.

Xamarin
  1. namespace DemoTest  
  2. {  
  3.     public partial class DemoTestPage : ContentPage  
  4.     {  
  5.         public DemoTestPage()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.   
  10.         void Add_Clicked(Object sender, System.EventArgs e)  
  11.         {  
  12.             lblresult.Text = "Result" + (Convert.ToInt32(valueAentry.Text) + Convert.ToInt32(valueBentry.Text)).ToString();  
  13.             DependencyService.Get<ItextToSpeech>().Speak(lblresult.Text);  
  14.         }  
  15.     }  
  16. }  

In this code, we are taking the values of entry1 and entry2 and for click event, we have written a program for SUM.

And the result is populated in level.

So, you we can test it. Just build the program and deploy on your simulator. After that, enter the values and click on the ADD button.

Now you will be able to listen to the value.

Xamarin

 

Conclusion

We have done a good practice for TextToSpeech implementation. We can implement it in our project based on the project requirement. This is very beneficial because we don’t have to use any plugin for this functionality.


Similar Articles