14

La siguiente es la forma de hacer que powershell hable.Powershell puede hablar, pero ¿puede escribir si hablo?

Add-Type -AssemblyName System.Speech 
$synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer 
$synthesizer.Speak('Hey, I can speak!') 

En realidad, me gustaría hacer lo contrario. Si hablo, puede PowerShell convertirlo en letras.

Si digo en mi grabadora "Hola, puedo hablar", ¿se convertirá en texto?

Si es posible, por favor, ¿me guía cómo lograrlo?

+0

No está seguro de si se puede escuchar, pero gracias por mostrar cómo se puede hablar, upvoted –

+0

Tenga en cuenta que estos son dos problemas diferentes dejar de fumar. – Joey

Respuesta

9

Parece que usted puede con System.Speech.Recognition. Aquí es posible ejemplo de uso, incluso por escrito en PowerShell:

http://huddledmasses.org/control-your-pc-with-your-voice-and-powershell/

Este enlace fue 404, así que lo sacó del camino de regreso de la máquina.

control de su PC con su voz ... y PowerShell

Por Joel Bennett 'Jaykul' el 25-Jun-2009

¿Alguna vez has querido ser capaz de hacer sus preguntas de ordenador y hacer que te responda ¿Alguna vez se preguntó si su computadora podría ser más parecida a Star Trek Enterprise, respondiendo a las consultas y comandos de voz? ¿Ha jugado con la automatización doméstica ZWave o X10 y pensó que el control de voz de sus dispositivos sería obvio? ¿próximo paso?

Bueno, vale ... No voy a mostrarte cómo encender las luces o trabajar con domótica, pero eso es lo que más me hace pensar en este reconocimiento de voz. ¿Qué geek no quiere entrar a la sala de estar y decir "Computadora: luces encendidas" y hacer que funcione?

En su lugar, como primer paso, le mostraré cómo usar PowerShell para hacer scripts simples de reconocimiento de comandos de voz ... ¡que pueden disparar cualquier script de PowerShell que quiera escribir! El código que sigue es realmente un módulo, aunque puede dot-source como un script, y realmente requiere PowerShell 2.0 para los eventos, aunque sería trivial refactorizarlo para que funcione en PowerShell 1.0 usando la biblioteca PSEventing de Oisin.

$null =[Reflection.Assembly]::LoadWithPartialName("System.Speech") 

## Create the two main objects we need for speech recognition and synthesis 
if(!$Global:SpeechModuleListener){## For XP's sake, don't create them twice... 
   $Global:SpeechModuleSpeaker =new-objectSystem.Speech.Synthesis.SpeechSynthesizer 
   $Global:SpeechModuleListener =new-objectSystem.Speech.Recognition.SpeechRecognizer 
} 

$Script:SpeechModuleMacros = @{} 
## Add a way to turn it off 
$Script:SpeechModuleMacros.Add("Stop Listening", { $script:listen =$false; Suspend-Listening }) 
$Script:SpeechModuleComputerName =${Env:ComputerName} 

function Update-SpeechCommands { 
#.Synopsis  
#  Recreate the speech recognition grammar 
#.Description 
#  This parses out the speech module macros,  
#  and recreates the speech recognition grammar and semantic results,  
#  and then updates the SpeechRecognizer with the new grammar,  
#  and makes sure that the ObjectEvent is registered. 
   $choices = new-objectSystem.Speech.Recognition.Choices 
   foreach($choice in$Script:SpeechModuleMacros.GetEnumerator()){ 
      New-ObjectSystem.Speech.Recognition.SemanticResultValue$choice.Key,  
                                                               $choice.Value.ToString() | 
         ForEach-Object{$choices.Add( $_.ToGrammarBuilder()) } 
   } 

   if($VerbosePreference -ne"SilentlyContinue") {$Script:SpeechModuleMacros.Keys |  
      ForEach-Object { Write-Host"$Computer, $_" -Fore Cyan } } 

   $builder = New-ObjectSystem.Speech.Recognition.GrammarBuilder"$Computer, " 
   $builder.Append((New-ObjectSystem.Speech.Recognition.SemanticResultKey"Commands",  
                                                         $choices.ToGrammarBuilder())) 
   $grammar = new-objectSystem.Speech.Recognition.Grammar$builder 
   $grammar.Name = "Power VoiceMacros" 

   ## Take note of the events, but only once (make sure to remove the old one) 
   Unregister-Event"SpeechModuleCommandRecognized" -ErrorAction SilentlyContinue 
   $null = Register-ObjectEvent$grammar SpeechRecognized ` 
               -SourceIdentifier"SpeechModuleCommandRecognized" ` 
               -Action { iex$event.SourceEventArgs.Result.Semantics.Item("Commands").Value} 
    
   $Global:SpeechModuleListener.UnloadAllGrammars() 
   $Global:SpeechModuleListener.LoadGrammarAsync($grammar ) 
} 

function Add-SpeechCommands { 
#.Synopsis 
#  Add one or more commands to the speech-recognition macros, and update the recognition 
#.Parameter CommandText 
#  The string key for the command to remove 
   [CmdletBinding()] 
   Param([hashtable]$VoiceMacros,[string]$Computer=$Script:SpeechModuleComputerName) 
    
   ## Add the new macros 
   $Script:SpeechModuleMacros +=$VoiceMacros  
   ## Update the default if they change it, so they only have to do that once. 
   $Script:SpeechModuleComputerName= $Computer  
   Update-SpeechCommands 
} 

function Remove-SpeechCommands { 
#.Synopsis 
#  Remove one or more command from the speech-recognition macros, and update the recognition 
#.Parameter CommandText 
#  The string key for the command to remove 
   Param([string[]]$CommandText) 
   foreach($command in $CommandText){$Script:SpeechModuleMacros.Remove($Command)} 
   Update-SpeechCommands 
} 

function Clear-SpeechCommands { 
#.Synopsis 
#  Removes all commands from the speech-recognition macros, and update the recognition 
#.Parameter CommandText 
#  The string key for the command to remove 
   $Script:SpeechModuleMacros = @{} 
   ## Default value: A way to turn it off 
   $Script:SpeechModuleMacros.Add("Stop Listening", { Suspend-Listening }) 
   Update-SpeechCommands 
} 


function Start-Listening { 
#.Synopsis 
#  Sets the SpeechRecognizer to Enabled 
   $Global:SpeechModuleListener.Enabled= $true 
   Say "Speech Macros are $($Global:SpeechModuleListener.State)" 
   Write-Host "Speech Macros are $($Global:SpeechModuleListener.State)" 
} 
function Suspend-Listening { 
#.Synopsis 
#  Sets the SpeechRecognizer to Disabled 
   $Global:SpeechModuleListener.Enabled= $false 
   Say "Speech Macros are disabled" 
   Write-Host "Speech Macros are disabled" 
} 

function Out-Speech { 
#.Synopsis 
#  Speaks the input object 
#.Description 
#  Uses the default SpeechSynthesizer settings to speak the string representation of the InputObject 
#.Parameter InputObject 
#  The object to speak  
#  NOTE: this should almost always be a pre-formatted string, 
#        most objects don't render to very speakable text. 
   Param([Parameter(ValueFromPipeline=$true)][Alias("IO")]$InputObject ) 
   $null =$Global:SpeechModuleSpeaker.SpeakAsync(($InputObject|Out-String)) 
} 

function Remove-SpeechXP { 
#.Synopis 
#  Dispose of the SpeechModuleListener and SpeechModuleSpeaker 
   $Global:SpeechModuleListener.Dispose();$Global:SpeechModuleListener = $null 
   $Global:SpeechModuleSpeaker.Dispose();$Global:SpeechModuleSpeaker = $null 
} 

set-alias asc Add-SpeechCommands 
set-alias rsc Remove-SpeechCommands 
set-alias csc Clear-SpeechCommands 
set-alias say Out-Speech 
set-alias listen Start-Listener 
Export-ModuleMember -Function * -Alias * -VariableSpeechModuleListener, SpeechModuleSpeaker 

Básicamente, hay una sola función que debe preocuparse aquí: New-VoiceCommands. Le pasas una tabla hash que asigna cadenas a scriptblocks, y si usas el -Listenswitch eso es todo lo que hay. También puede llamar a Start-Listening manualmente y, por supuesto, proporcioné la función Say para facilitar el uso de la computadora ...

Una vez que la computadora está "escuchando" ... simplemente diga su nombre, seguido por uno de tus comandos. Me gusta porque me garantiza que no ejecute las secuencias de comandos por accidente, pero puede eliminar la cadena ${Env:ComputerName}, desde el principio de GrammarBuilder si cree que no es necesario, o puede codificarla en un código que no sea el nombre de su computadora , como decir "Hal, por favor, te lo ruego ..." o "Computadora, por favor" o lo que sea.

Puedes hacer muchas cosas con esto ... cualquier cosa, en realidad ... pero para darte un ejemplo que puedas entender fácilmente, voy a hacer algo muy simple, y mi computadora solo responderá unas pocas preguntas básicas preguntas al responderme, y luego agregar algunos comandos para que comience una aplicación o una página web.

Add-SpeechCommands @{ 
   "What time is it?" = { Say "It is $(Get-Date -f "h:mm tt")" } 
   "What day is it?"  = { Say $(Get-Date -f "dddd, MMMM dd") } 
   "What's running?"  = { 
      $proc = ps | sort ws -desc 
      Say $("$($proc.Count) processes, including $($proc[0].name), which is using " + 
            "$([int]($proc[0].ws/1mb)) megabytes of memory") 
   } 
} -Computer "Laptop" -Verbose  

Add-SpeechCommands @{ "Run Notepad"= { &"C:\Programs\DevTools\Notepad++\notepad++.exe"} } 
Add-SpeechCommands @{ "Check Gee Mail" = { Start-Process"https://mail.google.com" } } 

Ves lo fácil que es? Puede utilizar “Di” para leer el texto (aunque SomeText va a obtener mejores resultados que otros), y se puede invocar cualquier otro comando de PowerShell, incluyendo HttpRest comandos para obtener los datos web, o los comandos WASP para la automatización de las ventanas, o los comandos PowerBoots para mostrar salida en texto grande, o cmdlets para controlar dispositivos X10 o ZWave ... ya sabes, cualquier cosa 

2

El reconocimiento de voz sigue siendo una tecnología experimental. Hay algunos .Net framework resources, incluso con un example. Sin embargo, no esperes crear un PowerShiri pronto.

1

La tecnología es un poco pasada "experimental", pero está lejos de ser confiable.

Cambio hace esto ahora con la opción "Buzón de Voz Vista previa" de la UM. Los resultados pueden variar de bastante buenos a hilarantes, dependiendo del orador.

Cuestiones relacionadas