如何在 PowerShell 7 中使用 Windows System.Speech for TTS(或者是否有替代方案)

hug*_*0ul 4 windows powershell text-to-speech powershell-core

我在 WindowsPowerShell 和 PowerShell 中都有相同的 profile.ps1。它包括调用 Windows Text-To-Speech 的命令,但是,这些命令在 PowerShell 7 中运行时会失败。

当我尝试使用我使用以下代码创建的 $PomrptTTS 对象时会发生错误:

Add-Type -AssemblyName System.speech
$PromptTTS = New-Object System.Speech.Synthesis.SpeechSynthesizer
Run Code Online (Sandbox Code Playgroud)

在 PowerShell 7 中,任何访问或使用我的 $PormptTTS 对象的尝试都会产生以下结果:

SetValueInvocationException: ....\profile.ps1:82
Line |
  82 |  $PromptTTS.Rate = 0 ; $PromptTTS.Speak("Time for the $((Get-Date).DayofWeek) shuffle")
     |  ~~~~~~~~~~~~~~~~~~~
     | Exception setting "Rate": "Object reference not set to an instance of an object."

MethodInvocationException: ....\profile.ps1:82
Line |
  82 |  … e = 0 ; $PromptTTS.Speak("Time for the $((Get-Date).DayofWeek) shuffle")
     |                                             ~~~~~~~~~~~~~~~~~~~~
     | Exception calling "Speak" with "1" argument(s): "Object reference not set to an instance of an object."
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 6

从 PowerShell 7.0 / .NET Core 3.1 开始,它System.Speech.Synthesis.SpeechSynthesizer视为仅限 .NET Framework 的 API,因此在 .NET Core 中不受支持。

解决方法是使用SAPI.SpVoiceCOM对象(在.NET Framework API最终基于,我相信):

$sp = New-Object -ComObject SAPI.SpVoice
$sp.Speak("Time for the $((Get-Date).DayOfWeek) shuffle")
Run Code Online (Sandbox Code Playgroud)

一个相关的问题询问更改说话的声音,不幸的是,由于 COM 支持有限,PowerShell Core 似乎不支持从 PowerShell 7.0 开始 - 请参阅此答案