0

I am trying to write the output of SpeechSynthesizer to a .wav file. If the synthesis is completed, everything works well and the output file is playable;

AudioStream = new FileStream(CurAudioFile, FileMode.Create);  
reader.SetOutputToWaveStream(AudioStream);
reader.SpeakAsynch(myPromptBuilder); 

But if I cancel the synthesis to the file through the following code (because the process is too long and I may want to cancel it) the output file produces no sound! (the produced file is not zero in size but nothing is played).

// On Cancel Button Clicked
reader.SpeakAsyncCancelAll();
while (reader.State == SynthesizerState.Speaking)
{
      Application.DoEvents();
}
// reader.SetOutputToNull();
AudioStream.Close();

I look for a solution in which I can cancel the audio generation, but the audio file can be played to the portion before it was canceled.

Is there any way I can achieve this?

4

1 回答 1

1

我不确定是否AsyncCancelAll将正确的结尾写入流,我建议在关闭流之前尝试刷新:

reader.SpeakAsyncCancelAll();
while (reader.State == SynthesizerState.Speaking)
{
      Application.DoEvents();
}
// reader.SetOutputToNull();
AudioStream.Flush();
AudioStream.Close();

如果这不起作用,那么我会说探索 API 指南:https://msdn.microsoft.com/en-us/library/system.speech.synthesis.speechsynthesizer.speakasynccancelall(v=vs.110)。 aspx

如果您找不到合适的 API 提供的解决方案,您可以考虑以下方法:

  1. 在后台线程上运行综合
  2. 跟踪开始时间和取消/结束时间
  3. 取消不会取消合成,只是记下它被取消的时间
  4. 所需的音频长度大致为(完成时间 - 开始时间)
  5. 合成完成后,您可以保存流然后对其进行修剪:Trim an Audio File(.wav,.mp3)

它可能不漂亮,但它可能会完成工作。

于 2015-04-23T13:57:15.207 回答