【问题标题】:Response.BinaryWrite creating a .partial file?Response.BinaryWrite 创建一个 .partial 文件?
【发布时间】:2014-03-05 15:20:11
【问题描述】:

我正在尝试将音频文件作为 .wav 写入内存流中的响应,以便客户端可以下载它。尝试打开具有“.partial”扩展名的文件时,它看起来像在客户端。就好像文件没有发布给客户端一样。

以下是我的代码...尝试将字节直接写入本地机器可以正常工作(您会看到代码被注释掉了)。

        // Initialize a new instance of the speech synthesizer.
        using (SpeechSynthesizer synth = new SpeechSynthesizer())
        using (MemoryStream stream = new MemoryStream())
        {

            // Create a SoundPlayer instance to play the output audio file.
            MemoryStream streamAudio = new MemoryStream();

            // Configure the synthesizer to output to an audio stream.
            synth.SetOutputToWaveStream(streamAudio);
            synth.Speak("This is sample text-to-speech output. How did I do?");
            streamAudio.Position = 0;

            // Set the synthesizer output to null to release the stream. 
            synth.SetOutputToNull();

            // Insert code to persist or process the stream contents here.
            // THIS IS NOT WORKING WHEN WRITING TO THE RESPONSE, .PARTIAL FILE CREATED
            Response.Clear();
            Response.ContentType = "audio/wav";
            Response.AppendHeader("Content-Disposition", "attachment; filename=mergedoutput.wav");
            Response.BinaryWrite(streamAudio.GetBuffer());
            Response.Flush();

            // THIS WORKS WRITING TO A FILE
            //System.IO.File.WriteAllBytes("c:\\temp\\als1.wav", streamAudio.GetBuffer());

        }

【问题讨论】:

    标签: c# asp.net httpresponse


    【解决方案1】:

    MemoryStream.GetBuffer 不是正确的调用方法:

    请注意,缓冲区包含可能未使用的已分配字节。 例如,如果将字符串“test”写入 MemoryStream 对象,GetBuffer返回的缓冲区长度是256,不是 4,有 252 个字节未使用。要仅获取缓冲区中的数据,请使用 ToArray 方法;但是, ToArray 在 记忆。

    所以请改用MemoryStream.ToArray

    Response.BinaryWrite(streamAudio.ToArray());
    

    【讨论】:

    • 更改为使用 ToArray 并且仍然具有相同的结果。奇怪的是使用上面代码中注释掉的行(WriteAllBytes 写入磁盘).wav 被保存并打开正常(甚至使用 GetBuffer())。
    • 我感觉我需要在页面指令中执行“Aysnc=true”这一事实可能会导致问题。但是,SpeechSynthesizer.Speak 方法需要这样做。
    【解决方案2】:

    看起来问题在于 speak 方法需要在自己的线程上运行。以下提供了正确取回字节数组然后能够将其写入响应的解决方案。

    C# SpeechSynthesizer makes service unresponsive

    【讨论】:

      猜你喜欢
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多