How to connect Cortana commands to custom scripts?

前端 未结 2 1901
栀梦
栀梦 2021-01-30 06:59

This may be a little early to ask this, but I\'m running Windows 10 Technical Preview Build 10122. I\'d like to set up Cortana to have custom commands. Here\'s how she works:

2条回答
  •  情深已故
    2021-01-30 07:46

    You can create commands for Cortana to listen for. These commands need to be described in a XML file called Voice Command Definitions or VCD.

    Here's an example:

    
    
        
            HomeControl
            Control alarm, temperature, light and others
    
            
                Activate alarm
                [Would] [you] [please] activate [the] alarm [please]
                Activate alarm
                Activate {builtin:AppName} alarm
                Activating alarm
                
            
            ...
        
    
    

    After create this definition, you need to register it at App Startup:

    protected async override void OnLaunched(LaunchActivatedEventArgs e)
    {
        ...
        // Install the VCD
        try
        {
            StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"HomeControlCommands.xml");
            await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("There was an error registering the Voice Command Definitions", ex);
        }
    }
    

    An then override the App.OnActivated method to handle when the events are triggered:

    protected override void OnActivated(IActivatedEventArgs e)
    {
        // Handle when app is launched by Cortana
        if (e.Kind == ActivationKind.VoiceCommand)
        {
            VoiceCommandActivatedEventArgs commandArgs = e as VoiceCommandActivatedEventArgs;
            SpeechRecognitionResult speechRecognitionResult = commandArgs.Result;
    
            string voiceCommandName = speechRecognitionResult.RulePath[0];
            string textSpoken = speechRecognitionResult.Text;
            IReadOnlyList recognizedVoiceCommandPhrases;
    
            System.Diagnostics.Debug.WriteLine("voiceCommandName: " + voiceCommandName);
            System.Diagnostics.Debug.WriteLine("textSpoken: " + textSpoken);
    
            switch (voiceCommandName)
            {
                case "Activate_Alarm":
                    System.Diagnostics.Debug.WriteLine("Activate_Alarm command");
                    break;
    

    The tutorial shows the complete code.

    After you do all of this, you can call your batch scripts using ProcessStartInfo or System.Diagnostics.Process.Start.

    Also, if you are interested in responding to the user through Cortana window, check this post regarding Cortana in background.

提交回复
热议问题