我想了解如何将variable.method输出的结果保存到另一个变量中。
我想测试创作一首歌但我仍然坚持如何继续。
目前语音输出本身但不保存在变量中。
他们的逻辑原因是什么?我只学了一个月的powershell。
Add-Type -AssemblyName System.Speech
$speak = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$man = $speak.Speak("Male Voice") # Outputs the Audio to host, but it does not store the result into Variable
$speak.SelectVoice("Microsoft Zira Desktop")
$woman = $speak.Speak("Female Voice")# Same as above
function song {
$man
$woman
song
}
答案 0 :(得分:1)
Speak
方法没有返回值
public void Speak(string textToSpeak)
但是可以通过SetOutputToWaveFile
将音频输入设置为文件
然后,您可以使用SoundPlayer
立即播放音频,以获得更好的用户体验。
Add-Type -AssemblyName System.Speech
$soundFilePath = "Test.wav"
# Save the Audio to a file
[System.Speech.Synthesis.SpeechSynthesizer] $voice = $null
Try {
$voice = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$voice.SetOutputToWaveFile($soundFilePath)
$voice.Speak("Male Voice")
$voice.SelectVoice("Microsoft Zira Desktop")
$voice.Speak("Female Voice")
} Finally {
# Make sure the wave file is closed
if ($voice) {
$voice.Dispose()
}
}
# Load the saved audio and play it back
[System.Media.SoundPlayer] $player = $null
Try {
$player = New-Object -TypeName System.Media.SoundPlayer($soundFilePath)
$player.PlaySync()
} Finally {
if ($player) {
$player.Dispose()
}
}
如果您只需要内存中的音频并且不想对任何内容进行后期处理,则可以将数据写入MemoryStream
。
Add-Type -AssemblyName System.Speech
[System.IO.MemoryStream] $memoryStream = $null;
Try {
$memoryStream = New-Object -TypeName System.IO.MemoryStream
[System.Speech.Synthesis.SpeechSynthesizer] $voice = $null
Try {
$voice = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$voice.SetOutputToWaveStream($memoryStream)
$voice.Speak("Male Voice")
$voice.SelectVoice("Microsoft Zira Desktop")
$voice.Speak("Female Voice")
} Finally {
if ($voice) {
$voice.Dispose()
}
}
# Load the saved audio and play it back
[System.Media.SoundPlayer] $player = $null
Try {
$memoryStream.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
$player = New-Object -TypeName System.Media.SoundPlayer($memoryStream)
$player.PlaySync()
} Finally {
if ($player) {
$player.Dispose()
}
}
} Finally {
if ($memoryStream) {
$memoryStream.Dispose()
}
}
答案 1 :(得分:0)
您无法将语音输出放入变量中,因为它不是函数返回的值,而是"副作用"。
但是没有必要存储音频。每次运行脚本时,只存储文本并生成语音输出会更有效。
编辑:我使用.SpeakAsync
和sleep
来更好地控制时间。调整延迟数,使其适合每条线的流量。
Add-Type -AssemblyName System.Speech
$male = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$male.SelectVoice("Microsoft David Desktop")
$female = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$female.SelectVoice("Microsoft Zira Desktop")
function male([string] $text, [int] $duration) {
$male.SpeakAsync($text) | Out-Null
sleep -Milliseconds $duration
}
function female([string] $text, [int] $duration) {
$female.SpeakAsync($text) | Out-Null
sleep -Milliseconds $duration
}
function song {
male 'hello' 500
female 'goodbye' 500
}
song