我想帮助理解如何将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
}发布于 2018-04-21 19:24:34
Speak方法没有返回值
public void ( 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()
}
}发布于 2018-04-21 20:50:07
您不能将语音输出放入一个变量中,因为它不是函数返回的值,而是一个“副作用”。
但不需要存储音频。只存储文本并在每次运行脚本时生成语音输出要有效得多。
编辑:我使用了.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
}
songhttps://stackoverflow.com/questions/49954898
复制相似问题