gpt4 book ai didi

c# - UWP 文本到列表框的语音 (c#')

转载 作者:行者123 更新时间:2023-11-30 23:29:24 26 4
gpt4 key购买 nike

我正在尝试实现文本到语音以按顺序从列表框中读取项目。最初,程序会同时读出所有相互重叠的项目。经过研究,我添加了一个 MediaEnded 处理程序,但我只能设法读出第一个项目,只有在这个实现的情况下。我将不胜感激任何帮助。

    private async void ToSpeechButton_Click(object sender, RoutedEventArgs e)
{
MediaElement mediaElement = new MediaElement();
var tsc = new TaskCompletionSource<bool>();
mediaElement.MediaEnded += (o, f) => { tsc.TrySetResult(true); };
mediaElement.Play();

foreach (var item in ListBox.Items)
{
readText(item.ToString());
await tsc.Task;
}

}


private async void readText(string mytext)
{
MediaElement mediaplayer = new MediaElement();
using (var speech = new SpeechSynthesizer())
{
speech.Voice = SpeechSynthesizer.AllVoices.First(gender => gender.Gender == VoiceGender.Female);
SpeechSynthesisStream stream = await speech.SynthesizeTextToStreamAsync(mytext);
mediaplayer.SetSource(stream, stream.ContentType);
mediaplayer.Play();
}
}

最佳答案

如果你阅读了 SpeechSynthesizer class 的文档, 你会发现有两种方法可以将文本转换为语音。一个是你用过的,SynthesizeTextToStreamAsync method ,此方法从字符串异步生成语音输出。

另一个是SynthesizeSsmlToStreamAsync method , 此方法从包含 Speech Synthesis Markup Language (SSML) 的字符串异步生成语音输出.

在这种情况下,我们可以使用 SynthesizeSsmlToStreamAsync在每个项目之间暂停语音的方法,例如:

private string allitem;

private void ToSpeechButton_Click(object sender, RoutedEventArgs e)
{
foreach (var item in listBox.Items)
{
var txt = item as ListBoxItem;
allitem += txt.Content.ToString() + "<break time='500ms'/>";
}
readText(allitem);
}

private async void readText(string mytext)
{
MediaElement mediaplayer = new MediaElement();
using (var speech = new SpeechSynthesizer())
{
speech.Voice = SpeechSynthesizer.AllVoices.First(gender => gender.Gender == VoiceGender.Female);
string ssml = @"<speak version='1.0' " + "xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" + allitem + "</speak>";
SpeechSynthesisStream stream = await speech.SynthesizeSsmlToStreamAsync(ssml);
mediaplayer.SetSource(stream, stream.ContentType);
mediaplayer.Play();
}
}

结合这个<break time='500ms'/>每个项目后的字符串,语音将在每个项目后暂停 500 毫秒。

关于c# - UWP 文本到列表框的语音 (c#'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com