如何正确处理SpeechSynthesizer以实现异步文本转语音?

时间:2019-03-14 17:20:42

标签: c# text-to-speech sapi speech-synthesis

我有一个表单,我希望允许用户每当按下按钮时就基于文本框的内容接收异步的文本到语音输出。对于上下文,此形式是作为VoiceAttack中“内部” C#函数的一部分启动的,并且是previous question的延续。该代码片段很好地完成了这项工作:

SpeechSynthesizer synth = new SpeechSynthesizer(); // Create new SpeechSynthesizer instance

// Function for asynchronous voicing of text with text-to-speech
public void VoiceText(string text)
{
    string MyVoice = null; // Initialize string for storing requested text-to-speech voice
    string DefaultVoice = null; // Initialize string for storing default Windows text-to-speech voice
    try // Attempt the following code...
    {
        synth.SpeakAsyncCancelAll(); // Cancels all queued, asynchronous, speech synthesis operations
        synth.Volume = 100; // Set the volume level of the text-to-speech voice
        synth.Rate = -2; // Set the rate at which text is spoken by the text-to-speech engine
        MyVoice = VA.GetText(">SDTTextToSpeechVoice") ?? "Not Set"; // Retrieve phonemes for processed text or set to null
        DefaultVoice = synth.Voice.Name; // Store the current default Windows text-to-speech voice
        if (MyVoice == "Default") // Check if requested voice name is "Default"
        {
            MyVoice = DefaultVoice; // Set MyVoice to the DefaultVoice
            VA.SetText(">SDTTextToSpeechVoice", MyVoice); // Redefine VoiceAttack text variable based on redefined MyVoice
        }
        synth.SelectVoice(MyVoice); // Set the voice for this instance of text-to-speech output
    }
    catch // Handle exceptions encountered in "try"
    {
        synth.SelectVoice(DefaultVoice); // Set the voice for this instance of text-to-speech output to the Windows default voice
        string VoiceList = null; // Initialize string variable for storing available text-to-speech voice names
        foreach (InstalledVoice v in synth.GetInstalledVoices()) // Loop through all available text-to-speech voices
            VoiceList += ", " + v.VoiceInfo.Name; // Add text-to-speech voice name to storage variable
        VA.WriteToLog("Text-to-speech voice '" + MyVoice + "' not found", "yellow"); // Output info to event log
        VA.WriteToLog("Valid TTS Voices = " + VoiceList.Trim(',', ' '), "yellow"); // Output info to event log
        VA.WriteToLog("Defaulting to current Windows text-to-speech voice (" + DefaultVoice + ")", "yellow"); // Output info to event log
    }
    synth.SpeakAsync(text); // Generate text-to-speech output asynchronously
}

// Function for disposing SpeechSynthesizer object
public void SpeechDispose()
{
    synth.Dispose(); // Releases resources tied to SpeechSynthesizer object
}

SpeechDispose()在表单关闭时被调用。我不能将合成器放在using()语句中,因为发声是异步的(我希望用户在再次按下按钮之前,不必强迫用户等待发声结束)。 是否有更好的清理方法?

0 个答案:

没有答案