Public/Invoke-Speech.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using namespace System.Speech.Synthesis

function Invoke-Speech
{
    [CmdletBinding(DefaultParameterSetName='String')]
    PARAM(
        [Parameter()][ValidateSet('David', 'Zira')][string]$Voice = 'Zira',
        [Parameter(Mandatory=$true,ParameterSetName='String',ValueFromPipeline=$true,Position=0,ValueFromRemainingArguments=$true)][string[]]$String,
        [Parameter(Mandatory=$true,ParameterSetName='Prompt',ValueFromPipeline=$true,Position=0,ValueFromPipelineByPropertyName=$true)][Prompt[]]$Prompt,
        [Parameter(Mandatory=$true,ParameterSetName='SSML',ValueFromPipeline=$true,Position=0,ValueFromPipelineByPropertyName=$true)][string[]]$SSMLString,
        [Parameter(Mandatory=$true,ParameterSetName='Time')][switch]$Time
    )

    begin
    {
        $Speaker = [SpeechSynthesizer]::new()
        if($Voice -eq 'Zira')
        {
            $Speaker.SelectVoiceByHints([VoiceGender]::Female)
        } else
        {
            $Speaker.SelectVoiceByHints([VoiceGender]::Male)
        }
    }

    process
    {
        $Type = $PSCmdlet.ParameterSetName
        if($Type -eq 'Time')
        {
            $String = [string[]]@("It is now $((Get-Date).ToShortTimeString())")
            $Type = 'String'
        }

        switch -Exact ($Type)
        {
            'String'
            {
                foreach($Item in $String)
                {
                    $Speaker.Speak($Item)
                }
            }

            'Prompt'
            {
                foreach($Item in $Prompt)
                {
                    $Speaker.Speak($Item)
                }
            }

            'SSML'
            {
                foreach($Item in $SSMLString)
                {
                    if($Item)
                    {
                        $Speaker.SpeakSsml($Item)
                    }
                }
            }
        }
    }

    end
    {
        $Speaker.Dispose();
    }
}