Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#

Introduction
 
In this article, we are going to learn how to convert a text into speech in multiple languages using an important Cognitive Service APIs called Microsoft Text-to-Speech Service API ( One of the APIs in Speech API ). The Text to Speech (TTS) API of the Speech service converts an input text into natural-sounding speech (also called speech synthesis). It supports text in multiple languages and gender-based voice (male or female) selection.
 
You can also refer to the following articles on Cognitive Services. 
Prerequisites
  1. Subscription key ( Azure Portal ) or ( Trial Subscription Key ).
  2. Visual Studio 2015 or 2017
Convert Text to Speech API
 
First, we need to log into the Azure Portal with our login credentials. Then, we need to create an Azure Speech Service API on the Azure portal. So, please click on the "Create a resource" on the left top menu and search for "Speech" in the search bar on the right side window or top of Azure Marketplace.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
 
Now, we can see there are some speech-related “AI + Machine Learning” categories listed in the search result.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
 
Click on the "Create" button to create the Speech Service API.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
Provision a Speech Service API ( Text to Speech ) Subscription Key
 
After clicking "Create", it will open another window. There, we need to provide the basic information of Speech API. 
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
 
Name - Name of the Translator Text API ( Eg. TextToSpeechApp ).
 
Subscription - We can select our Azure subscription for Speech API creation.
 
Location - We can select a location of the resource group. The best thing is that we can choose a location closest to our customer.
 
Pricing tier - Select an appropriate pricing tier for your requirement.
 
Resource group - We can create a new resource group or choose from an existing one ( We created a new resource group as "SpeechResource" ).
 
Now, click on the "TextToSpeechApp" in the dashboard page and it will redirect to the detailed page of TextToSpeechApp ( "Overview" ). Here, we can see the "Keys" ( subscription key details ) menu on the left side panel. Then, click on the “Keys” menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text to speech conversion using Microsoft Speech Service API.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
 
Authentication
 
A token ( bearer ) based authentication is required in the Text To Speech conversion using Speech Service API. So we need to create an authentication token using "TextToSpeechApp" subscription keys. The following "endPoint" will help to create an authentication token for Text to speech conversion. Each access token is valid for 10 minutes and after that, we need to create a new one for the next process.
  1. https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken  
Speech Synthesis Markup Language ( SSML )
 
The Speech Synthesis Markup Language (SSML) is an XML-based markup language that provides a way to control the pronunciation and rhythm of text-to-speech. More about SSML.
 
SSML Format :
  1. <speak version='1.0' xml:lang='en-US'><voice xml:lang='ta-IN' xml:gender='Female' name='Microsoft Server Speech Text to Speech Voice (ta-IN, Valluvar)'>  
  2.         நன்றி  
  3. </voice></speak>  
How to make a request
 
This is a very simple process. An HTTP request is made in the POST method. That means we need to pass the secure data in the request body and that will be a plain text or an SSML document. As per the documentation, it is clearly mentioned in most cases that we need to use SSML body as a request. The maximum length of the HTTP request body is 1024 characters and the following is the endPoint for our HTTP Post method.
  1. https://westus.tts.speech.microsoft.com/cognitiveservices/v1  
The following are the HTTP headers required in the request body.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C#
 Pic source : https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-text-to-speech 
 
Index.html
 
The following HTML contains the binding methodology that we have used in our application by using the latest Tag helpers of ASP.NET Core.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C# 
 
Model
 
The following model contains the Speech Model information.
  1. using Microsoft.AspNetCore.Mvc.Rendering;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4.    
  5. namespace TextToSpeechApp.Models  
  6. {  
  7.     public class SpeechModel  
  8.     {  
  9.         public string Content { getset; }  
  10.    
  11.         public string SubscriptionKey { getset; } = "< Subscription Key >";  
  12.    
  13.         [DisplayName("Language Selection :")]  
  14.         public string LanguageCode { getset; } = "NA";  
  15.    
  16.         public List<SelectListItem> LanguagePreference { getset; } = new List<SelectListItem>  
  17.         {  
  18.         new SelectListItem { Value = "NA", Text = "-Select-" },  
  19.         new SelectListItem { Value = "en-US", Text = "English (United States)"  },  
  20.         new SelectListItem { Value = "en-IN", Text = "English (India)"  },  
  21.         new SelectListItem { Value = "ta-IN", Text = "Tamil (India)"  },  
  22.         new SelectListItem { Value = "hi-IN", Text = "Hindi (India)"  },  
  23.         new SelectListItem { Value = "te-IN", Text = "Telugu (India)"  }  
  24.         };  
  25.     }  
  26. }  
Interface
 
The "ITextToSpeech" contains one signature for converting text to speech based on the given input. So we have injected this interface in the ASP.NET Core “Startup.cs” class as "AddTransient".
  1. using System.Threading.Tasks;  
  2.    
  3. namespace TextToSpeechApp.BusinessLayer.Interface  
  4. {  
  5.     public interface ITextToSpeech  
  6.     {  
  7.         Task<byte[]> TranslateText(string token, string key, string content, string lang);  
  8.     }  
  9. }  
Text to Speech API Service
 
We can add the valid Speech API Subscription key and authentication token to the following code.
  1. ///   
  2.    
  3. <summary>  
  4.         /// Translate text to speech  
  5.         /// </summary>  
  6.    
  7.    
  8.         /// <param name="token">Authentication token</param>  
  9.         /// <param name="key">Azure subscription key</param>  
  10.         /// <param name="content">Text content for speech</param>  
  11.         /// <param name="lang">Speech conversion language</param>  
  12.         /// <returns></returns>  
  13.         public async Task<byte[]> TranslateText(string token, string key, string content, string lang)  
  14.         {  
  15.             //Request url for the speech api.  
  16.             string uri = "https://westus.tts.speech.microsoft.com/cognitiveservices/v1";  
  17.             //Generate Speech Synthesis Markup Language (SSML)   
  18.             var requestBody = this.GenerateSsml(lang, "Female"this.ServiceName(lang), content);  
  19.    
  20.             using (var client = new HttpClient())  
  21.             using (var request = new HttpRequestMessage())  
  22.             {  
  23.                 request.Method = HttpMethod.Post;  
  24.                 request.RequestUri = new Uri(uri);  
  25.                 request.Headers.Add("Ocp-Apim-Subscription-Key", key);  
  26.                 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);  
  27.                 request.Headers.Add("X-Microsoft-OutputFormat""audio-16khz-64kbitrate-mono-mp3");  
  28.                 request.Content = new StringContent(requestBody, Encoding.UTF8, "text/plain");  
  29.                 request.Content.Headers.Remove("Content-Type");  
  30.                 request.Content.Headers.Add("Content-Type""application/ssml+xml");  
  31.                 request.Headers.Add("User-Agent""TexttoSpeech");  
  32.                 var response = await client.SendAsync(request);  
  33.                 var httpStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);  
  34.                 Stream receiveStream = httpStream;  
  35.                 byte[] buffer = new byte[32768];  
  36.    
  37.                 using (Stream stream = httpStream)  
  38.                 {  
  39.                     using (MemoryStream ms = new MemoryStream())  
  40.                     {  
  41.                         byte[] waveBytes = null;  
  42.                         int count = 0;  
  43.                         do  
  44.                         {  
  45.                             byte[] buf = new byte[1024];  
  46.                             count = stream.Read(buf, 0, 1024);  
  47.                             ms.Write(buf, 0, count);  
  48.                         } while (stream.CanRead && count > 0);  
  49.    
  50.                         waveBytes = ms.ToArray();  
  51.    
  52.                         return waveBytes;  
  53.                     }  
  54.                 }  
  55.             }  
  56.         }  
Download
Demo
Output
 
The given text is converted into speech in the desired language listed in a drop-down list using Microsoft Speech API.
 
Convert Text To Speech In Multiple Languages Using ASP.NET Core And C# 
Reference
See Also
 
You can download other source codes from MSDN Code, using the link, mentioned below.
 
Summary
 
From this article, we have learned how to convert a text into speech in multiple languages using ASP.NET Core and C# as per the API documentation using Text-to-Speech API. I hope this article is useful for all Azure Cognitive Services API beginners. 


Similar Articles