Last active
May 12, 2017 09:45
-
-
Save ksasao/859a65efddf7cd620cdd66965dc74d6f to your computer and use it in GitHub Desktop.
UWP の連続音声認識のサンプルコード ( https://blogs.msdn.microsoft.com/shintak/2016/07/22/constraintrecognition/ ) に音声入力がタイムアウトした場合の継続処理を追加。Package.appxmanifest の Capabilities で Microphone にチェックを入れるのを忘れずに。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// An empty page that can be used on its own or navigated to within a Frame. | |
/// </summary> | |
public sealed partial class MainPage : Page | |
{ | |
public MainPage() | |
{ | |
this.InitializeComponent(); | |
} | |
//連続音声認識のためのオブジェクト | |
private SpeechRecognizer contSpeechRecognizer; | |
private CoreDispatcher dispatcher; | |
protected async override void OnNavigatedTo(NavigationEventArgs e) | |
{ | |
//ハックグラウンドスレッドからUIスレッドを呼び出すためのDispatcher | |
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; | |
//初期化 | |
contSpeechRecognizer = | |
new Windows.Media.SpeechRecognition.SpeechRecognizer(); | |
await contSpeechRecognizer.CompileConstraintsAsync(); | |
//認識中の処理定義 | |
contSpeechRecognizer.HypothesisGenerated += | |
ContSpeechRecognizer_HypothesisGenerated; | |
contSpeechRecognizer.ContinuousRecognitionSession.ResultGenerated += | |
ContinuousRecognitionSession_ResultGenerated; | |
// 音声入力ないままタイムアウト(20秒位)した場合の処理 | |
contSpeechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed; | |
//認識開始 | |
await contSpeechRecognizer.ContinuousRecognitionSession.StartAsync(); | |
} | |
private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args) | |
{ | |
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => | |
{ | |
textBlock1.Text = "Timeout."; | |
}); | |
// 音声を再度待ち受け | |
await contSpeechRecognizer.ContinuousRecognitionSession.StartAsync(); | |
} | |
private async void ContSpeechRecognizer_HypothesisGenerated( | |
SpeechRecognizer sender, SpeechRecognitionHypothesisGeneratedEventArgs args) | |
{ | |
//認識途中に画面表示 | |
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => | |
{ | |
textBlock1.Text = args.Hypothesis.Text; | |
}); | |
} | |
private async void ContinuousRecognitionSession_ResultGenerated( | |
SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args) | |
{ | |
//認識完了後に画面に表示 | |
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => | |
{ | |
textBlock1.Text = "Waiting ..."; | |
output.Text += args.Result.Text + "。\n"; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment