我正在使用这个完美无缺的代码,除非我想添加能够知道startSpeaking
通话何时完成通话。
static class VoiceEffect
{
SpeechSynthesizer reader = new SpeechSynthesizer();
private volatile bool _isCurrentlySpeaking = false;
/// <summary>Event handler. Fired when the SpeechSynthesizer object starts speaking asynchronously.</summary>
private void StartedSpeaking(object sender, SpeakStartedEventArgs e)
{ _isCurrentlySpeaking = true; }
/// <summary>Event handler. Fired when the SpeechSynthesizer object finishes speaking asynchronously.</summary>
private void FinishedSpeaking(object sender, SpeakCompletedEventArgs e)
{ _isCurrentlySpeaking = false; }
private VoiceEffect _instance;
/// <summary>Gets the singleton instance of the VoiceEffect class.</summary>
/// <returns>A unique shared instance of the VoiceEffect class.</returns>
public VoiceEffect GetInstance()
{
if(_instance == null)
{ _instance = new VoiceEffect(); }
return _instance;
}
/// <summary>
/// Constructor. Initializes the class assigning event handlers for the
/// SpeechSynthesizer object.
/// </summary>
private VoiceEffect()
{
reader.SpeakStarted += new EventHandler<SpeakStartedEventArgs>(StartedSpeaking);
reader.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(FinishedSpeaking);
}
/// <summary>Speaks stuff.</summary>
/// <param name="str">The stuff to speak.</param>
public void startSpeaking(string str)
{
reader.Rate = -2; // Voice effects.
reader.Volume = 100;
// if the reader's currently speaking anything,
// don't let any incoming prompts overlap
while(_isCurrentlySpeaking)
{ continue; }
reader.SpeakAsync(str);
}
/// <summary>Creates a new thread to speak stuff into.</summary>
/// <param name="str">The stuff to read.</param>
public void createVoiceThread(string str)
{
Thread voicethread = new Thread(() => startSpeaking(str)); // Lambda Process
voicethread.IsBackground = true;
voicethread.Start();
}
}
来自这个问题https://stackoverflow.com/a/17153718/1137006
我通过在另一个类中写这个来调用它:
TextToSpeech.startSpeaking(text);
我想知道这个电话什么时候完成并且讲完了。 可能作为一个事件? 我可以在VoiceEffect类中看到该事件,但我不知道如何在执行startSpeaking()调用的类中触发它。 我需要知道的原因是在发言之后改变WPF控制。 是否可以添加到此代码中?
修改:澄清
在我的MainWindow类中,我可以从具有VoiceEffect类和startSpeaking方法的TextToSpeech.cs文件中调用多个TextToSpeech。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TextToSpeech.startSpeaking("Test1");
TextToSpeech.startSpeaking("Test2");
TextToSpeech.startSpeaking("Test3");
TextToSpeech.startSpeaking("Test4");
}
}
他们都会在讲话之前等待前一次完成,并且在演讲期间让节目继续前进。
我想知道我是否可以获得一个事件或某些事情,例如“Test2”已经说过,然后在MainWindow中更改WPF控件?例如,隐藏文本标签。
答案 0 :(得分:2)
这是你在找什么?
public MainWindow() {
InitializeComponent();
SpeechSynthesizer reader = new SpeechSynthesizer();
reader.SpeakCompleted += Reader_SpeakCompleted;
}
void Reader_SpeakCompleted(object sender, SpeakCompletedEventArgs e) {
}