There are times where small and simple things can have big impact for a larger audience, one example is implementing a Text To Speech function. Users want to interact with machines in a smarter and meaningful way, the biggest challenge is for developers and engineers to meet that expectation integrating those features in their solutions.
We always give for granted that notifications are visual and users are always staring in front of a monitor waiting for a pop-up window or a new line on the cli to check progress or output of a repetitive operation.
But I think that in many cases text to speech is a good way getting user attention or providing useful instructions. So let’s dive into..
PowerShell Text To Speech
Let’s start with a PowerShell example:
1 2 3 |
Add-Type –AssemblyName System.Speech $SpeechSynthesizer = New-Object –TypeName System.Speech.Synthesis.SpeechSynthesizer $SpeechSynthesizer.Speak('Hello, World!') |
As we all know, Powershell is built on top of .NET Framework, so we can directly point to a class such System.Speech.Syntesis.SpeechSynthesizer .
Looking at the object’s properties we can modify:
- Rate (speed /speaking rate)
- State ( status of the SpeechSynthesizer)
- Voice (Change voice gender/ culture/ etc..)
- Volume (Volume of the SpeechSynthesizer).
To start from the beginning, we need a direct reference to the .NET Object
1 2 |
Add-Type –AssemblyName System.Speech $SpeechSynthesizer = New-Object –TypeName System.Speech.Synthesis.SpeechSynthesizer |
Let’s check the new object created:
1 |
PS> $SpeechSynthesizer |
This will be the output :
1 2 3 |
State Rate Volume Voice ----- ---- ------ ----- Ready 0 100 System.Speech.Synthesis.VoiceInfo |
Now, let’s check the voice used:
1 2 3 4 5 6 7 8 9 10 11 |
PS> $SpeechSynthesizer.voice Gender : Male Age : Adult Name : Microsoft David Desktop Culture : en-US Id : TTS_MS_EN-US_DAVID_11.0 Description : Microsoft David Desktop - English (United States) SupportedAudioFormats : {} AdditionalInfo : {[Age, Adult], [Gender, Male], [Language, 409], [Name, Microsoft David Desktop]...} |
List all the installed voice
1 2 3 |
Foreach ($voice in $SpeechSynthesizer.GetInstalledVoices()){ $Voice.VoiceInfo | Select-Object Gender, Name, Culture, Description } |
With this result:
1 2 3 4 |
Gender Name Culture Description ------ ---- ------- ----------- Male Microsoft David Desktop en-US Microsoft David Desktop - English (United States) Female Microsoft Zira Desktop en-US Microsoft Zira Desktop - English (United States) |
How to change/select the voice
If I want to change my voice with a Female voice:
1 2 |
$SpeechSynthesizer.SelectVoice("Microsoft Zira Desktop") $SpeechSynthesizer.Speak('Hello, World!') |
As usual, you can find the source code and these examples on my GitHub repository.