Windows Phone 8 新增功能:TTS文字朗讀功能 和 語音識別 API

l_serein發表於2013-03-27

一:Windows Phone 8 提供了TTS文字朗讀功能API介面
需要新增 ID_CAP_SPEECH_RECOGNITION  能力,

只需要簡單的兩段程式碼就可以完成文字輸出,

[csharp] view plaincopy
  1. SpeechSynthesizer synthesizer = new SpeechSynthesizer();  
  2. await synthesizer.SpeakTextAsync("好好學習,天天向上");  


 

二: Windows Phone 8 提供了語音識別內嵌程式內的API

需要新增 ID_CAP_SPEECH_RECOGNITION  ID_CAP_NETWORKING ID_CAP_MICROPHONE 三種能力,

對於app既可以通過類 SpeechRecognizerUI 直接呼叫系統語音控制元件,也可以通過類 SpeechRecognizer 和 SpeechSynthesizer 類的組合實現自定義控制元件

參考程式碼來自官方例子 Short message dictation and web search grammars sample

 

 

[csharp] view plaincopy
  1. /*  
  2.     Copyright (c) 2012 Microsoft Corporation.  All rights reserved. 
  3.     Use of this sample source code is subject to the terms of the Microsoft license  
  4.     agreement under which you licensed this sample source code and is provided AS-IS. 
  5.     If you did not accept the terms of the license agreement, you are not authorized  
  6.     to use this sample source code.  For the terms of the license, please see the  
  7.     license agreement between you and Microsoft. 
  8.    
  9.     To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604  
  10.    
  11. */  
  12. using Microsoft.Phone.Controls;  
  13. using System;  
  14. using System.Windows;  
  15. using Windows.Phone.Speech.Recognition;  
  16.   
  17. namespace sdkSpeechPredefinedGrammarsWP8CS  
  18. {  
  19.     public partial class MainPage : PhoneApplicationPage  
  20.     {  
  21.         SpeechRecognizerUI speechRecognizer;  
  22.   
  23.         // Constructor  
  24.         public MainPage()  
  25.         {  
  26.             InitializeComponent();  
  27.   
  28.             this.speechRecognizer = new SpeechRecognizerUI();  
  29.         }  
  30.   
  31.         private async void btnShortMessageDictation_Click(object sender, RoutedEventArgs e)  
  32.         {  
  33.             this.speechRecognizer.Recognizer.Grammars.Clear();  
  34.   
  35.             // Use the short message dictation grammar with the speech recognizer.  
  36.             this.speechRecognizer.Recognizer.Grammars.AddGrammarFromPredefinedType("message", SpeechPredefinedGrammar.Dictation);  
  37.   
  38.             await this.speechRecognizer.Recognizer.PreloadGrammarsAsync();  
  39.   
  40.             try  
  41.             {  
  42.                 // Use the built-in UI to prompt the user and get the result.  
  43.                 SpeechRecognitionUIResult recognitionResult = await this.speechRecognizer.RecognizeWithUIAsync();  
  44.   
  45.                 if (recognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)  
  46.                 {  
  47.                     // Output the speech recognition result.  
  48.                     txtDictationResult.Text = "You said: " + recognitionResult.RecognitionResult.Text;  
  49.                 }  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 MessageBox.Show(ex.Message);  
  54.             }  
  55.         }  
  56.   
  57.         private async void btnWebSearch_Click(object sender, RoutedEventArgs e)  
  58.         {  
  59.             this.speechRecognizer.Recognizer.Grammars.Clear();  
  60.   
  61.             this.speechRecognizer.Recognizer.Grammars.AddGrammarFromPredefinedType("search", SpeechPredefinedGrammar.WebSearch);  
  62.   
  63.             await this.speechRecognizer.Recognizer.PreloadGrammarsAsync();  
  64.   
  65.             try  
  66.             {  
  67.                 // Use the built-in UI to prompt the user and get the result.  
  68.                 SpeechRecognitionUIResult recognitionResult = await this.speechRecognizer.RecognizeWithUIAsync();  
  69.   
  70.                 if (recognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)  
  71.                 {  
  72.                     // Output the speech recognition result.  
  73.                     this.txtWebSearchResult.Text = "You said: " + recognitionResult.RecognitionResult.Text;  
  74.                 }  
  75.   
  76.             }  
  77.             catch (Exception ex)  
  78.             {  
  79.                 MessageBox.Show(ex.Message);  
  80.             }  
  81.         }  
  82.     }  
  83. }  


 

參考程式碼來自官方例子 Speech recognition and text-to-speech sample

 

[csharp] view plaincopy
  1. /*  
  2.     Copyright (c) 2012 Microsoft Corporation.  All rights reserved. 
  3.     Use of this sample source code is subject to the terms of the Microsoft license  
  4.     agreement under which you licensed this sample source code and is provided AS-IS. 
  5.     If you did not accept the terms of the license agreement, you are not authorized  
  6.     to use this sample source code.  For the terms of the license, please see the  
  7.     license agreement between you and Microsoft. 
  8.    
  9.     To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604  
  10.    
  11. */  
  12. using Microsoft.Phone.Controls;  
  13. using System;  
  14. using System.Collections.Generic;  
  15. using System.Windows;  
  16. using System.Windows.Media;  
  17. using Windows.Foundation;  
  18. using Windows.Phone.Speech.Recognition;  
  19. using Windows.Phone.Speech.Synthesis;  
  20.   
  21. namespace sdkSpeechColorChangeWP8CS  
  22. {  
  23.     public partial class MainPage : PhoneApplicationPage  
  24.     {  
  25.         Dictionary<string, SolidColorBrush> _colorBrushes;  
  26.   
  27.         SpeechSynthesizer synthesizer;  
  28.         SpeechRecognizer recognizer;  
  29.         IAsyncOperation<SpeechRecognitionResult> recoOperation;  
  30.   
  31.         bool _isNew = true;  
  32.         bool recoEnabled = false;  
  33.   
  34.         // Constructor  
  35.         public MainPage()  
  36.         {  
  37.             InitializeComponent();  
  38.         }  
  39.   
  40.         protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)  
  41.         {  
  42.             // On first run, set up the dictionary of SolidColorBrush objects.   
  43.             if (_isNew)  
  44.             {  
  45.                 _colorBrushes = new Dictionary<string, SolidColorBrush>();  
  46.                 _colorBrushes.Add("red"new SolidColorBrush(Colors.Red));  
  47.                 _colorBrushes.Add("cyan"new SolidColorBrush(Colors.Cyan));  
  48.                 _colorBrushes.Add("blue"new SolidColorBrush(Colors.Blue));  
  49.                 _colorBrushes.Add("yellow"new SolidColorBrush(Colors.Yellow));  
  50.                 _colorBrushes.Add("orange"new SolidColorBrush(Colors.Orange));  
  51.                 _colorBrushes.Add("fire color"new SolidColorBrush(Colors.Magenta));  
  52.                 _colorBrushes.Add("purple"new SolidColorBrush(Colors.Purple));  
  53.                 _colorBrushes.Add("black"new SolidColorBrush(Colors.Black));  
  54.                 _colorBrushes.Add("jet black"new SolidColorBrush(Colors.Black));  
  55.                 _colorBrushes.Add("green"new SolidColorBrush(Colors.Green));  
  56.                 _colorBrushes.Add("white"new SolidColorBrush(Colors.White));  
  57.                 _colorBrushes.Add("dark gray"new SolidColorBrush(Colors.DarkGray));  
  58.                 _colorBrushes.Add("brown"new SolidColorBrush(Colors.Brown));  
  59.                 _colorBrushes.Add("magenta"new SolidColorBrush(Colors.Magenta));  
  60.                 _colorBrushes.Add("gray"new SolidColorBrush(Colors.Gray));  
  61.                 _isNew = false;  
  62.             }  
  63.   
  64.             try  
  65.             {  
  66.                 // Create the speech recognizer and speech synthesizer objects.   
  67.                 if (this.synthesizer == null)  
  68.                 {  
  69.                     this.synthesizer = new SpeechSynthesizer();  
  70.                 }  
  71.                 if (this.recognizer == null)  
  72.                 {  
  73.                     this.recognizer = new SpeechRecognizer();  
  74.                 }  
  75.                 // Set up a list of colors to recognize.  
  76.                 this.recognizer.Grammars.AddGrammarFromList("Colors"new List<string>() { "red""cyan""blue""yellow""orange""fire color""purple""black""jet black""green""white""dark gray""brown""magenta""gray" });  
  77.             }  
  78.             catch (Exception err)  
  79.             {  
  80.                 txtResult.Text = err.ToString();  
  81.             }  
  82.   
  83.             base.OnNavigatedTo(e);  
  84.         }  
  85.   
  86.         private async void btnContinuousRecognition_Click(object sender, RoutedEventArgs e)  
  87.         {  
  88.             // Change the button text.   
  89.             if (this.recoEnabled)  
  90.             {  
  91.                 this.recoEnabled = false;  
  92.                 this.btnContinuousRecognition.Content = "Start speech recognition";  
  93.                 txtResult.Text = String.Empty;  
  94.                 this.recoOperation.Cancel();  
  95.                 return;  
  96.             }  
  97.             else  
  98.             {  
  99.                 this.recoEnabled = true;  
  100.                 this.btnContinuousRecognition.Content = "Cancel speech recognition";  
  101.             }  
  102.   
  103.             while (this.recoEnabled)  
  104.             {  
  105.                 try  
  106.                 {  
  107.                     // Perform speech recognition.    
  108.                     this.recoOperation = recognizer.RecognizeAsync();  
  109.                     var recoResult = await this.recoOperation;  
  110.   
  111.                     // Check the confidence level of the speech recognition attempt.  
  112.                     if ((int)recoResult.TextConfidence < (int)SpeechRecognitionConfidence.Medium)  
  113.                     {  
  114.                         // If the confidence level of the speech recognition attempt is low,   
  115.                         // ask the user to try again.  
  116.                         txtResult.Text = "Not sure what you said, please try again.";  
  117.                         await synthesizer.SpeakTextAsync("Not sure what you said, please try again");  
  118.                     }  
  119.                     else  
  120.                     {  
  121.                         // Output that the color of the rectangle is changing by updating  
  122.                         // the TextBox control and by using text-to-speech (TTS).   
  123.                         txtResult.Text = "Changing color to: " + recoResult.Text;  
  124.                         await synthesizer.SpeakTextAsync("Changing color to " + recoResult.Text);  
  125.   
  126.                         // Set the fill color of the rectangle to the recognized color.   
  127.                         rectangleResult.Fill = getBrush(recoResult.Text.ToLower());  
  128.                     }  
  129.                 }  
  130.                 catch (System.Threading.Tasks.TaskCanceledException)  
  131.                 {   
  132.                     // Ignore the cancellation exception of the recoOperation.  
  133.                 }  
  134.                 catch (Exception err)  
  135.                 {  
  136.                     // Handle the speech privacy policy error.  
  137.                     const int privacyPolicyHResult = unchecked((int)0x80045509);  
  138.   
  139.                     if (err.HResult == privacyPolicyHResult)  
  140.                     {  
  141.                         MessageBox.Show("You must accept the speech privacy policy to continue.");  
  142.                         this.recoEnabled = false;  
  143.                         this.btnContinuousRecognition.Content = "Start speech recognition";  
  144.                     }  
  145.                     else  
  146.                     {  
  147.                         txtResult.Text = "Error: " + err.Message;  
  148.                     }  
  149.                 }  
  150.             }  
  151.   
  152.         }  
  153.   
  154.         /// <summary>  
  155.         /// Returns a SolidColorBrush that matches the recognized color string.  
  156.         /// </summary>  
  157.         /// <param name="reco">The recognized color string.</param>  
  158.         /// <returns>The matching colored SolidColorBrush.</returns>  
  159.         private SolidColorBrush getBrush(string recognizedColor)  
  160.         {  
  161.             if (_colorBrushes.ContainsKey(recognizedColor))  
  162.                 return _colorBrushes[recognizedColor];  
  163.   
  164.             return new SolidColorBrush(Colors.White);  
  165.         }  
  166.     }  
  167. }  


 

相關文章