Al Belmondo
Al Belmondo

Reputation: 784

Response.BinaryWrite creating a .partial file?

I am attempting to write an audio file as a .wav in a memorystream out to the response so the client can download it. It looks like on client side when trying to open the file it has a ".partial" extension. It is almost as if the file is not getting released to the client.

The below is my code... Attempting to write the bytes directly to the local machine works fine (you will see that code commented out).

        // 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());

        }

Upvotes: 0

Views: 706

Answers (2)

Al Belmondo
Al Belmondo

Reputation: 784

Looks like the issue was the fact the speak method needs to be run on its own thread. The following provides the solution to get back the byte array properly and then be able to write that to the response.

C# SpeechSynthesizer makes service unresponsive

Upvotes: 0

Alberto
Alberto

Reputation: 15941

MemoryStream.GetBuffer is not the correct method to call:

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

so use MemoryStream.ToArray instead:

Response.BinaryWrite(streamAudio.ToArray());

Upvotes: 1

Related Questions