首页 > 解决方案 > 尝试使用 SpeechSynthesizer 和 NAudio 但进程无法访问该文件

问题描述

我正在尝试使用 SpeechSynthesizer 和 NAduio,我的代码如下。我似乎无法让它工作。我收到错误消息,

该进程无法访问文件“some file.wav”,因为它正被另一个进程使用。

它发生在线上,

波 = 新 WaveFileReader(路径 + 文件名);

在 synth_SpeakCompleted 方法中。

我不明白什么在使用该文件?引发事件后,SpeechSynthesizer 已完成文件的创建。显然我错过了一些东西。

我只是保存文件,因为我不知道如何直接从 SpeechSynthesizer 转到 NAudio,所以如果有一个解决方案不能保存文件,那就太好了。

该文件很好,当我手动运行它时可以完美运行。

      using NAudio.Wave;

      public partial class MainWindow : Window
      {

        private WaveFileReader wave = null;
        private DirectSoundOut output = null;
        SpeechSynthesizer synthesizer = null;

        private void DrawContent()
        {
              string path = @"C:\Users\MyPath\";
              string fileName = "MyFile.wav";

              // delete previous file if it exists
              if (File.Exists(path + fileName))
                  File.Delete(path + fileName);

              synthesizer = new SpeechSynthesizer();
              synthesizer.Volume = 100;  // 0...100
              synthesizer.Rate = 3;     // -10...10

              synthesizer.SetOutputToWaveFile(path + fileName);
              synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synth_SpeakCompleted);
              synthesizer.SpeakAsync(someText);



         }

    void synth_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {

        synthesizer.SetOutputToNull();

        string path = @"C:\Users\MyPath\";
        string fileName = "MyFile.wav";

        wave = new WaveFileReader(path + fileName);
        output = new DirectSoundOut();
        output.Init(new WaveChannel32(wave));
        output.Play();

    }

    private void DisposeWave()
    {
        if(output != null)
        {
            if (output.PlaybackState == PlaybackState.Playing)
                output.Stop();

            output.Dispose();
            output = null;
        }

        if(wave != null)
        {
            wave.Dispose();
            wave = null;
        }
    }


  }

标签: c#.netnaudiospeech-synthesisspeechsynthesizer

解决方案


推荐阅读