Windows Phone 8 / Windows 8 : Intégrer Cortana dans une application

Mais qu’est-ce que Cortana?
Cortana est le nom de l’assistant personnel virtuel développé par Microsoft pour sa plateforme Windows Phone à partir de la version 8.1. Il concurrence les assistants Siri d’Apple et Google Now.
Cortana est actuellement disponible en anglais, en français, en allemand, en italien, en espagnol et en chinois (sous le nom de Xiao Na).
Pour bien commencer…
Il vous faudra installer Visual Studio 2013 Update 4 ou Visual Studio 2013 Community (gratuit).
Vous pouvez obtenir Visual Studio 2013 Community en le téléchargeant sur le site Visual Studio de Microsoft.
Comment lancer son application depuis Cortana?
Tout d’abord, ajoutez une VoiceCommandDefinition à votre projet.
Définissez la langue de vos phrases via l’attribut xml:lang du noeud CommandSet.
<CommandSet xml:lang="fr-fr">
Maintenant, définissez la commande avec laquelle vous allez préfixer toutes vos demandes. Ceci afin de guider Cortana vers la bonne application à lancer.
<CommandPrefix>Cellenza</CommandPrefix>
Ensuite, il vous reste à définir une commande :
<Command Name="cortanaitems"> <Example>Affiche moi les éléments du site</Example> <ListenFor>{show} [moi] [les] éléments du site</ListenFor> <Feedback>Affichage des éléments du site...</Feedback> <Navigate Target="/Views/CortanaListItems.xaml" /> </Command> <PhraseList Label="show"> <Item>affiche</Item> <Item>montre</Item> <Item>cherche</Item> <Item>recherche</Item> <Item>trouve</Item> </PhraseList>
Une commande est construite de la manière suivante :
- Son nom
- Un exemple pour l’utilisateur que Cortana proposera à l’utilisateur s’il lui demande « Que puis-je dire ?»
- La phrase que Cortana va tenter de reconnaître
Dans notre exemple la phrase est constituée de mots facultatifs ( entre [] ) et de synonymes ( entre {} la référence à une liste de phrases « PhraseList »). - La cible de la commande
Voici dans notre cas le fichier utilisé lors de l’événement Cortana & SharePoint : from Zero to Hero.
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.0"> <CommandSet xml:lang="fr-fr"> <!-- The CommandPrefix provides an alternative to your full app name for invocation --> <CommandPrefix>Cellenza</CommandPrefix> <!-- The CommandSet Example appears in the global help alongside your app name --> <Example> affiche les documents de site</Example> <Command Name="cortanaitems"> <Example>Affiche moi les éléments du site</Example> <ListenFor>{show} [moi] {items} du site</ListenFor> <Feedback>Affichage des éléments du site...</Feedback> <Navigate Target="/Views/CortanaListItems.xaml" /> </Command> <Command Name="cortanaappointments"> <Example>Montre moi le calendrier du site</Example> <ListenFor>{show} [moi] {events} du site</ListenFor> <Feedback>Affichage des évènements du site...</Feedback> <Navigate Target="/Views/CortanaListItems.xaml" /> </Command> <Command Name="cortanasearch"> <Example>Trouve dans le site</Example> <ListenFor>{show} dans le site</ListenFor> <Feedback>Affichage des résultats du site...</Feedback> <Navigate Target="/Views/CortanaSearch.xaml" /> </Command> <PhraseList Label="show"> <Item>affiche</Item> <Item>montre</Item> <Item>cherche</Item> <Item>recherche</Item> <Item>trouve</Item> </PhraseList> <PhraseList Label="items"> <Item>documents</Item> <Item>éléments</Item> </PhraseList> <PhraseList Label="events"> <Item>calendrier</Item> <Item>évènements</Item> </PhraseList> </CommandSet> </VoiceCommands>
Une fois ce fichier créé, il ne vous reste plus qu’à dire à votre application de charger ce fichier de reconnaissance et comment réagir aux commandes.
Vous devrez charger ce fichier au sein de l’événement OnNavigatedTo :
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { if (e.NavigationMode == NavigationMode.New) { var storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync (new Uri("ms-appx:///VoiceCommandDefinition.xml")); await Windows.Media.SpeechRecognition.VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(storageFile); } }
Au sein de l’App.xaml, il vous faudra dans l’événement OnActivated savoir si votre application a été lancée via Cortana. Heureusement, nous avons cette information au sein de la propriété Kind des arguments passés à l’événement.
if (args.Kind == ActivationKind.VoiceCommand){}
Ensuite, il nous suffit de savoir quelle a été la commande qui vient d’être lancée et d’effectuer les actions souhaitées. Dans notre cas, afficher des pages.
var rootFrame = EnsureRootFrame(); var commandArgs = args as Windows.ApplicationModel.Activation.VoiceCommandActivatedEventArgs; Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; string voiceCommandName = speechRecognitionResult.RulePath[0]; switch (voiceCommandName) { case "cortanaitems": rootFrame.Navigate(typeof(CortanaListItems), null); break; case "cortanaappointments": rootFrame.Navigate(typeof(CortanaCalendar), null); break; case "cortanasearch": rootFrame.Navigate(typeof(CortanaSearch), null); break; default: rootFrame.Navigate(typeof(MainPage), null); break; } } base.OnActivated(args); } /// <summary> /// Ensures that the window has a root Frame. /// </summary> private static Frame EnsureRootFrame() { var rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; // Place the frame in the current Window Window.Current.Content = rootFrame; } return rootFrame; }
Vous pouvez désormais utiliser votre application depuis Cortana 😉
Comment utiliser la reconnaissance vocale au sein de votre application?
Pour « parler » depuis votre application, il suffit d’utiliser la classe SpeechRecognition. Il vous faudra également penser à ajouter l’utilisation du microphone dans les paramètres de votre projet.
Windows.Globalization.Language langFR = new Windows.Globalization.Language("fr-FR"); SpeechRecognizer recognizer = new SpeechRecognizer(langFR); SpeechRecognitionTopicConstraint topicConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "Development"); recognizer.Constraints.Add(topicConstraint); await recognizer.CompileConstraintsAsync(); // Required var recognition = recognizer.RecognizeAsync(); recognition.Completed += this.Recognition_Completed;
Une fois que Cortana estime que vous avez fini de parler, l’événement « Completed » est levé. C’est donc à ce moment-là que nous allons traiter le résultat de l’écoute.
/// <summary> /// Speech recognition completed. /// </summary> private async void Recognition_Completed(IAsyncOperation<SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus) { var results = asyncInfo.GetResults(); if (results.Confidence != SpeechRecognitionConfidence.Rejected) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new DispatchedHandler( () => { This.txtCortanaMessages.Text = results.Text })); } else { this.txtCortanaMessages.Text = "Désolé, je n'ai pas compris."; } }
Le résultat de l’écoute sera sous la forme d’une chaîne de caractères.
Et… Voilà !
Pour télécharger le projet de l’exemple, rendez-vous sur l’article dédié à notre événement Cortana & SharePoint : from Zero to Hero.
Pour vous rendre sur le github, c’est par ici que ça se passe !