Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Text to Speech in .Net and .Net Micro Framework, with translation too!

While the thought of a cube farm filled with talking computers is the stuff of nightmares for many (well for me anyway, there's enough chatter already, and to add to it every PC verbally chatting away too? AHHHhhhh... lol), building speech capabilities into our hardware projects is something many of us would like to do. Having our weather station tell us when something is important happening, our robot asking us to get out of the way, our robotank issuing final ultimatums, etc., etc.

But we also would like it to be easy and cheap too. Oh yeah, and it would also be cool if we could auto-magically support different languages.

Sounds like a mission for the Cloud, doesn't it?

Today's Hardware Friday comes to us from Marco Minerva via his New version of Text-To-Speech library post and is just that, Text to Speech, for .Net and the .Net Micro Framework, powered by the Azure DataMarket based Microsoft Translator Service.

Text-To-Speech (Speech Synthesis) with Microsoft Translator Service

This library uses the Microsoft Translator Service to obtain streams of file speaking text in the desired language. At the moment of writing, there are 44 supported languages, including English, Italian, German, French, Spanish, Japanese and Chinese.

If you're looking for the .NET Micro Framework of this library, go to http://code.msdn.microsoft.com/Text-To-Speech-for-NET-9cea4462.

Building the Sample

The code you can download from this page contains a Class Library, named TranslatorService.Speech, that provides all you need to add speech synthesis functionalities to your applications. It also includes a small Console Application,TranslatorSpeakExample, that shows a basic example of its usage.

To run the application, you need to to go to Azure DataMarket and obtain the Client ID and Client Secret to use the service.

Description

The library makes calls to the Microsoft Translator Service using the classic HttpWebRequest .NET object and process the REST response. So, its usage is very simple

Text-To-Speech for .NET Micro Framework with Microsoft Translator Service

This library uses the Microsoft Translator Service to obtain streams of file speaking text in the desired language. At the moment of writing, there are 44 supported languages, including English, Italian, German, French, Spanish, Japanese and Chinese.

If you're looking for the .NET Framework version of this library, go to http://code.msdn.microsoft.com/Speech-Synthesis-with-7658fa03.

Building the Sample

The code you can download from this page contains a Class Library, named MicroTranslatorService.Speech, that provides all you need to add speech synthesis functionalities to your .NET Micro Framework applications. It also includes a small .NET Micro Framework project,TranslatorSpeakExample, that shows a basic example of its usage.

To run the application, you need to to go to Azure DataMarket, and obtain the Client ID and Client Secret to use the service.

Description

The library makes calls to the Microsoft Translator Service using the HttpWebRequest .NET Micro Framework object and process the REST response. So, its usage is very simple:

If you're new to the Azure DataMarket, like I was, you might not know what "you need to to go to Azure DataMarket and obtain the Client ID and Client Secret to use the service." really means, where to find create or find your "Client ID and Client Secret."

Microsoft Translator - Obtaining an Access Token

You must obtain an access token to use the Microsoft Translator API. The access token is passed with each API call and is used to authenticate your access to the Microsoft Translator API. It provides a secure access to the Microsoft Translator API and allows the API to associate your application’s requests to the Microsoft Translator service with your account on Azure Marketplace.

Microsoft provides methods to obtain access tokens safely, repeatedly, and easily. To obtain an access token, perform the following steps:

  1. Subscribe to the Microsoft Translator API on Azure Marketplace
  2. Register your application Azure DataMarket
  3. Make an HTTP POST request to the token service
1. Subscribe to the Microsoft Translator API on Azure Marketplace

Subscribe to the Microsoft Translator API on Azure Marketplace. Basic subscriptions, up to 2 million characters a month, are free. Translating more than 2 million characters per month requires a payment. You may pick from any of the available subscription offers.

2. Register your application Azure DataMarket

To register your application with Azure DataMarket, visit https://datamarket.azure.com/developer/applications/ using the LiveID credentials from step 1, and click on “Register”. In the “Register your application” dialog box, you can define your own Client ID and Name. The redirect URI is not used for the Microsoft Translator API. However, the redirect URI field is a mandatory field, and you must provide a URI to obtain the access code. A description is optional.
Take a note of the client ID and the client secret value.

...

Snaps for Step 1 above;

image

image

image

Snaps for Step 2 above;

image

image

Now take the Client Id and Client secret and paste it into the app;

SNAGHTML56b3235f

Now you should be good to go!

Run it and start playing. It's really kind of fun listening to the different translations (though I have no clue what they are saying...lol)

SNAGHTML56b4fdf5

SNAGHTML56b40516

Here's a snap of the .Net version Solution;

image

static void Main(string[] args)
       {
           if (string.IsNullOrEmpty(CLIENT_ID) || string.IsNullOrEmpty(CLIENT_SECRET))
           {
               Console.WriteLine("You must obtain a Client ID and Secret in order to use this application. Please visit Azure DataMarket at https://datamarket.azure.com/developer/applications to get one.\n");
               Console.ReadKey();
               return;
           }

           // Create the object to retrieve spoken streams.
           SpeechSynthesizer speech = new SpeechSynthesizer(CLIENT_ID, CLIENT_SECRET);
           speech.SpeakCompleted += new EventHandler<SpeechEventArgs>(speech_SpeakCompleted);
           speech.AudioFormat = SpeakStreamFormat.Wave;
           speech.AudioQuality = SpeakStreamQuality.MaxQuality;

           Console.WriteLine("Retrieving the list of supported languages...");
           try
           {
               string[] languages = speech.GetLanguages();

               Console.WriteLine("Found {0} supported languges:", languages.Length);
               foreach (var lang in languages)
               {
                   Console.WriteLine("{0} - {1}", lang, CultureInfo.GetCultureInfo(lang).DisplayName);
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine("Error during the request: {0}", ex.Message);
           }

           Console.WriteLine("\n");

           bool quit = false;            
           while (!quit)
           {
               try
               {
                   Console.Write("Insert the text to be spoken (empty to terminate): ");
                   string text = Console.ReadLine();
                   if (string.IsNullOrWhiteSpace(text))
                   {
                       quit = true;
                       continue;
                   }

                   Console.Write("Specify the text language (empty to terminate): ");
                   string language = Console.ReadLine();
                   if (string.IsNullOrWhiteSpace(language))
                   {
                       quit = true;
                       continue;
                   }

                   Console.Write("Submitting request... ");

                   // Retrieve the stream of wave-file speaking the passed-in text in the desired language. 
                   //using (Stream stream = speech.GetSpeakStream(text, language))
                   //{
                   //    var length = stream.Length;
                   //    using (SoundPlayer player = new SoundPlayer(stream))
                   //        player.PlaySync();
                   //}

                   // Speak the passed-in text in the desired language, in an asynchronous way.
                   // When this operation completes, the speech_SpeakCompleted event is raised.
                   speech.SpeakAsync(text, language);
               }
               catch (Exception ex)
               {
                   Console.WriteLine("Error during the request: {0}", ex.Message);
               }

               Console.WriteLine("\n");
           }
       }

       private static void speech_SpeakCompleted(object sender, SpeechEventArgs e)
       {
           if (e.Error != null)
               Console.WriteLine("Erorr: " + e.Error.Message);
       }
   }

The TranslatorService.Speech assembly is pretty easy to understand and well documented;

 

/// <summary>
     /// Initializes a new instance of the <strong>SpeechSynthesizer</strong> class, using the specified Client ID and Client Secret and the desired language.
     /// </summary>
     /// <param name="clientID">The Application Client ID.
     /// </param>
     /// <param name="clientSecret">The Application Client Secret.
     /// </param>
     /// <param name="language">A string representing the supported language code to speak the text in. The code must be present in the list of codes returned from the method <see cref="GetLanguages"/>.</param>
     /// <remarks>You must register your application on Azure DataMarket, https://datamarket.azure.com/developer/applications, to obtain the Client ID and Client Secret needed to use the service.
     /// </remarks>
     /// <seealso cref="ClientID"/>
     /// <seealso cref="ClientSecret"/>        
     /// <seealso cref="Language"/>
     public SpeechSynthesizer(string clientID, string clientSecret, string language)
     {
         ClientID = clientID;
         ClientSecret = clientSecret;
         Language = language;
         AudioFormat = SpeakStreamFormat.Wave;
         AudioQuality = SpeakStreamQuality.MinSize;
     }

     #region Get Languages

     /// <summary>
     /// Retrieves the languages available for speech synthesis.
     /// </summary>
     /// <returns>A string array containing the language codes supported for speech synthesis by <strong>Microsoft Translator Service</strong>.</returns>        
     /// <exception cref="ArgumentException">The <see cref="ClientID"/> or <see cref="ClientSecret"/> properties haven't been set.</exception>
     /// <remarks><para>This method will block until the array is returned. If you want to perform a non-blocking request to be notified when the operation is completed, use the <see cref="GetLanguagesAsync"/> method instead.</para>
     /// <para>For more information, go to http://msdn.microsoft.com/en-us/library/ff512415.aspx.
     /// </para>
     /// </remarks>
     /// <seealso cref="GetLanguagesAsync"/>
     public string[] GetLanguages()
     {
         // Check if it is necessary to obtain/update access token.
         this.UpdateToken();

         string uri = LANGUAGES_URI;
         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
         httpWebRequest.Headers.Add(AUTHORIZATION_HEADER, headerValue);

         if (Proxy != null)
             httpWebRequest.Proxy = Proxy;

         using (WebResponse response = httpWebRequest.GetResponse())
         {
             using (Stream stream = response.GetResponseStream())
             {
                 DataContractSerializer dcs = new DataContractSerializer(typeof(string[]));
                 string[] results = (string[])dcs.ReadObject(stream);

                 return results;
             }
         }
     }

If you're looking to add speech, as in text to speech, with automatic machine translation into different languages to your .Net app or .Net Micro Framework project, you should run, not walk, and check this out...

 

Page image, nabaztag, courtesy of habi

Tags:

Follow the Discussion

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.