I was playing around with some Powershell scripts over the weekend and came across a very interesting object:
SAPI.SPVoice
This object lets you generate speech from text and is very easy to use. I’ve included a few samples here to show just how easy!
In this example, we call our simple function with the text we want to hear. We also have an optional switch parameter called -SLOW that will change the speed of the speech, just for fun. This example is using a ComObject to generate the speech.
# # This first section will generate speech from text using a ComObject # function Say-Text1 { param( [Parameter(Mandatory=$true)] $Text, [switch] $Slow ) $object = New-Object -ComObject SAPI.SpVoice if ($Slow) { $object.Rate = -10 } $object.Speak($text) | Out-Null } Say-Text1 "Testing One, Two, Three!" Say-Text1 "Testing Four and Five!" -Slow # #
In the next example, we will use .NET to create the speech. We again call our function with the text we want to hear. By default, we have the speech running as a synchronous command.
(This simpy means that the speech will have to finish before moving on to the next command.)
We added another optional switch parameter for this one, however, if you want the command to run asynchronously instead (-ASYNC).
NOTE: When using the -ASYNC parameter, if you have multiple speech statements right after each other, the speech will be ‘clobbered’, as if two or more people were trying to speak at exactly the same time.
# # The next section will generate speech from text using .NET function Say-Text2 { param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [string] $Text, [switch] $Async=$false ) [Reflection.Assembly]::LoadWithPartialName('System.Speech') | Out-Null $object = New-Object System.Speech.Synthesis.SpeechSynthesizer if ($Async) { $object.SpeakAsync($Text) } else { $object.Speak($Text) } } Say-Text2 "Testing Six, Seven and eight!" Say-Text2 "Testing Nine and Ten! Then we wait 10 seconds." -Async start-sleep 10 # #
You can even read in a text file and have it converted to speech for you as well! Here is a quick example of how to do it:
# # First we just create the ComObject $voice = new-object -ComObject "SAPI.SPVoice" # Then we use the new object to speak! This command is spoken synchronously. $voice.speak("Powershell rocks!") # And this minor change reads in and speaks a text file asynchronously. $voice.Speak( "h:\scripts\callme.bat", 5 ) start-sleep 20 # #
So there you have it! Text to Speech via Powershell is quick and easy!
— PFM