Click here to Skip to main content
Click here to Skip to main content

Text to Speech in Windows Phone 7

By , 23 Nov 2011
 

Introduction

This article discusses how to use Cloud-based Microsoft Translator Service in Windows phone 7 to translate text to speech.  

Background

In this article, I am going to explain how we can take the leverage of cloud to solve the problem of Text to Speech translation. It’s pretty simple to archive such kind of functionality in Windows Phone 7 using Bing API. Here I will show how we can retrieve a list of languages supported by Microsoft Translator for the Speech API and speak the user’s input text.

First of all, we must obtain a valid Bing API AppID, let's follow the below steps.

Step 1: Open the below mentioned URL to register your application, and follow the instructions to obtain a valid Bing API AppID.

1.png - Click to enlarge image

Step 2: Enter required information and obtain a valid Bing API AppID.

2.png - Click to enlarge image 

Once you register your application, now we will be moving ahead with the Windows phone 7 application developments and invoke the cloud service.

Step 3: Create a Windows phone 7 application project:

WP_001.png - Click to enlarge image

Step 4: To add web reference of the Microsoft Translator Service, we need to add a service reference to Windows Phone project. Right click the Windows Phone Project in solution explorer, and choose Add Service Reference. Please see the below pictures for the same.

WP_004.png

WP_003.png

WP_004.png

Step 5: Now add a panorama page to Windows phone 7 project.

WP_005.png - Click to enlarge image

Step 6: Create a UI as per application requirement, see below XAML code snippet. Here I have added three panorama items. 

Using the XAML Code for UI Construction

<Grid x:Name="LayoutRoot">
    <controls:Panorama Title="text to speech" Name="panoSpeech" 
           Foreground="Blue" FontFamily="Comic Sans MS">
        <!--Panorama item one-->
        <controls:PanoramaItem Header="Language(s)" 
               Foreground="Plum" FontFamily="DengXian" 
               FontSize="72">
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <DataTemplate x:Key="LanguageTemplate">
                        <TextBlock Foreground="White" 
                           Margin="0,0,0,0" Text="{Binding Name}"  />
                    </DataTemplate>
                </StackPanel.Resources>
                    <ListBox HorizontalAlignment="Left" 
                       ItemTemplate="{StaticResource LanguageTemplate}" 
                       Margin="20,10,0,20" 
                       Name="ListLanguages" Width="441">
                    </ListBox>
            </StackPanel>
        </controls:PanoramaItem>

        <!--Panorama item two-->
        <controls:PanoramaItem Header="Speech" Foreground="Yellow">
            <StackPanel Orientation="Vertical" Margin="20,0,0,0">
                <TextBox Name="TextToSpeachText" 
                   Text="This Pavan Pareta, Microsoft Most Value able professional. 
                         He has written an application for windows phone 7" 
                   TextWrapping="Wrap" Height="350" />
                <Button Content="S p e a k" Height="90" 
                   Margin="0,30,0,0" Name="btnSpeak" 
                   Width="338" Click="btnSpeak_Click" />
            </StackPanel>
        </controls:PanoramaItem>

        <!--Panorama item three-->
        <controls:PanoramaItem Header="Speak" Foreground="Violet">
            <StackPanel Orientation="Vertical">
                <Image Height="auto" Name="image1" 
                   Stretch="None" Width="auto" 
                   Margin="50 60 80 0" Source="/speak.jpg" />
            </StackPanel>
        </controls:PanoramaItem>
    </controls:Panorama>
</Grid>

Step 7: First Panorama item used to develop for retrieving supported speech languages. To retrieve the supported language, we need to call web service method “GetLanguagesForSpeakAsync”. The GetLanguagesForSpeak method only returns the language codes, for example, en for English and fr for French, etc. See the below UI and code snippet.

WP_006.png

GetLanguagesForSpeakAsync takes two methods like AppID and object

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        FrameworkDispatcher.Update();
        var objTranslator = new ServiceReference1.LanguageServiceClient();
        objTranslator.GetLanguagesForSpeakCompleted += 
          new EventHandler<GetLanguagesForSpeakCompletedEventArgs>(
          translator_GetLanguagesForSpeakCompleted);
        objTranslator.GetLanguagesForSpeakAsync(AppId, objTranslator);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

void translator_GetLanguagesForSpeakCompleted(object sender, 
                GetLanguagesForSpeakCompletedEventArgs e)
{
    var objTranslator = e.UserState as ServiceReference1.LanguageServiceClient;
    objTranslator.GetLanguageNamesCompleted += 
      new EventHandler<GetLanguageNamesCompletedEventArgs>(
      translator_GetLanguageNamesCompleted);
    objTranslator.GetLanguageNamesAsync(AppId, "en", e.Result, e.Result);
}

void translator_GetLanguageNamesCompleted(object sender, 
     GetLanguageNamesCompletedEventArgs e)
{
    var codes = e.UserState as ObservableCollection<string>;
    var names = e.Result;
    var languagesData = (from code in codes
                     let cindex = codes.IndexOf(code)
                     from name in names
                     let nindex = names.IndexOf(name)
                     where cindex == nindex
                     select new TranslatorLanguage()
                     {
                         Name = name,
                         Code = code
                     }).ToArray();
    this.Dispatcher.BeginInvoke(() =>
    {
        this.ListLanguages.ItemsSource = languagesData;
    });
}

Step 8: Second Panorama item used to develop for speak text using SpeakAsync method takes four string parameters like AppId, SpeechText, SpeechLanguage, format. See the below UI and code snippet.

WP_007.png

private void btnSpeak_Click(object sender, RoutedEventArgs e)
{
    var languageCode = "en";
    var language = this.ListLanguages.SelectedItem as TranslatorLanguage;
    if (language != null)
    {
        languageCode = language.Code;
    }
    var objTranslator = new ServiceReference1.LanguageServiceClient();
    objTranslator.SpeakCompleted += translator_SpeakCompleted;
    objTranslator.SpeakAsync(AppId, this.TextToSpeachText.Text, 
                             languageCode, "audio/wav");

    panoSpeech.DefaultItem = panoSpeech.Items[(int)2];            
 }

void translator_SpeakCompleted(object sender, ServiceReference1.SpeakCompletedEventArgs e)
{
    var client = new WebClient();
    client.OpenReadCompleted += ((s, args) =>
    {
        SoundEffect se = SoundEffect.FromStream(args.Result);
        se.Play();
    });
            client.OpenReadAsync(new Uri(e.Result));
}

Step 9: Now build the application and execute it.  

WP_008.png

WP_009.png

WP_010.png

Points of Interest

FrameworkDispatcher.Update(), Bing API which allows speech to written text. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PavanPareta
Software Developer (Senior)
India India
Member
Pavan is a Senior software developer, and has been in the industry since August 2005. He has experience in Windows Phone 7, Windows Mobile with Compact Framework, Python for S60, C#.NET, VB.NET, Windows Forms, ASP.NET, WCF, Silverlight, JavaScript and HTML.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSend it to Email Too?memberalan933 Apr '13 - 14:12 
Is there a way to send it to Email too?
I had a program called Voice To Text but I don't see it in the market place anymore.
If this is possible to add to this project it would be great!
QuestionHi.About Credential Of Web ServicememberMember 395610926 Mar '13 - 7:19 
Hi. I'm connecting one web service on windows phone 7. but it connects with credential. I can't connect with credential. Can you help me?
hello

QuestionText To Speech with problemmemberMember 86142172 Oct '12 - 7:56 
Hello, I have a problem, can someone help me?
After upgrading to the azure I'm not getting this same application running, someone could make it work?
QuestionNew MS Translator FormatmemberBowo Fadoju7 Aug '12 - 17:30 
Yes, Bing APIs are now deprecated, my library for text-to-speech can be found
here[^], however it is very limited and if you want to implement more functions before I update it, use my library for obtaining the required token here[^]
NewsLooks like the Bing APIs are now Deprecated and thus you can't use thismvp_ Kunal Chowdhury _13 Jun '12 - 22:13 
Hi Pavan,
 
Just going through your article and noticed that the Bing APIs are now Deprecated and thus you can't use this for the time being. I hope, Microsoft will reactivate it earliest by 1st August 2012.
 
Otherwise, the article was good and you deserve a 5-vote from me. Cheers...
Regards - Kunal Chowdhury
Microsoft MVP (Silverlight) | Codeproject MVP & Mentor | Telerik MVP

 
Follow me on: My Technical Blog | Silverlight-Zone | Twitter | Facebook | Google+

QuestionNeed help!memberzenith.tav13 May '12 - 17:55 
Dear all,
 
Few weeks ago I used these codes and it worked properly. Now when trying to use them one more time I face a new problem in Reference.cs file:
 
Quote:
System.ServiceModel.FaultException was unhandled
Message=ArgumentException: Invalid appId
Parameter name: appId : ID=3643.V2_Soap.GetLanguagesForSpeak.2202BB90
StackTrace:
at System.ServiceModel.DiagnosticUtility.ExceptionUtility.BuildMessage(Exception x)
at System.ServiceModel.DiagnosticUtility.ExceptionUtility.LogException(Exception x)
at System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(Exception e)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at TextToSpeech.ServiceReference1.LanguageServiceClient.LanguageServiceClientChannel.EndGetLanguagesForSpeak(IAsyncResult result)
at TextToSpeech.ServiceReference1.LanguageServiceClient.TextToSpeech.ServiceReference1.LanguageService.EndGetLanguagesForSpeak(IAsyncResult result)
at TextToSpeech.ServiceReference1.LanguageServiceClient.OnEndGetLanguagesForSpeak(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.CallComplete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.FinishSend(IAsyncResult result, Boolean completedSynchronously)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.SendCallback(IAsyncResult result)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()

 
Please help me if anybody know what's going on?!
AnswerRe: Need help!memberrenaud_25623 May '12 - 12:37 
I'm guessing it's related to the migration
 
Quote:
Developers with existing AppIDs can continue using Bing Search API 2.0 until August 1, 2012. On and after this date, Bing Search API 2.0 AppIDs will no longer return results. Developers can continue using the API by signing up for it in the Windows Azure Marketplace. Read the Migration Guide and FAQs to get started.

:(
GeneralMy vote of 1member3boddddd7 May '12 - 22:05 
not much useful if i want to costomize it to fit for my needs.
QuestionBing APIs are deprecated. Any helpmemberSantiago Sanchez28 Apr '12 - 7:18 
Hi Pavan,
 
first of all, thank you for this nice article. I tried it a few months ago and it worked ok.
 
Now, I am developing a new WP7 application related with the speech service but I have found out that Bing APIS are deprecated.
 
Any help on this?
 
Thank you and best regards.
QuestionRecord possiblememberyogarajan20 Feb '12 - 21:50 
can i record this voice it is possible?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 23 Nov 2011
Article Copyright 2011 by PavanPareta
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid