Mikki Maus
Mikki Maus

Reputation: 43

Create WAV stream in memory

I have a URL to MP4 audio file that I need to send to Speech-To-Text API. The API accepts only WAV stream. I am using NAudio 1.7.3 and the following code to download the file and to get the appropriate stream to be sent to API:

string filePath = "C:\Windows\Temp\file.wav";
using (MediaFoundationReader reader = new MediaFoundationReader(audioFileURL))
{
    WaveFileWriter.CreateWaveFile(filePath, reader);
}
System.IO.FileStream fs = new FileStream(filePath, FileMode.Open);

Then I send the fs stream to API and everything works correctly, although very slowly because of I/O to/from disk.

I decided to rewrite this code and execute all required in memory. For this purpose I wrote the following code (that does not provide me a correct stream):

using (MediaFoundationReader reader = new MediaFoundationReader(audioLocation)){
    MemoryStream ms = new MemoryStream();
    IgnoreDisposeStream ids = new IgnoreDisposeStream(ms);
    WaveFileWriter writer = new WaveFileWriter(ids, reader.WaveFormat);

    //Doing one of the following (both provide the same outcome):
    //1. reader.CopyTo(ids);
    //or 
    //2. this code from NAudio source:
    var buffer = new byte[reader.WaveFormat.AverageBytesPerSecond * 4];
    while (true)
    {
        int bytesRead = reader.Read(buffer, 0, buffer.Length);
        if (bytesRead == 0)
        {
            // end of source provider
            break;
        }
        // Write will throw exception if WAV file becomes too large
        writer.Write(buffer, 0, bytesRead);
    }

    writer.Dispose();
    Stream streamToSendToAPI = ids.SourceStream;

    //Send streamToSendToAPI to Speech-To-Text API

}

My expectation is that using second code example, where I create stream with WAV header and then add the data to the stream, would provide me a valid WAV stream. However, when I send it to speech-to-text API, the API gives error that indicates that stream cannot be processed (meaning that stream is invalid).

Please advise how to fix the in-memory code example to create a valid WAV stream

Upvotes: 2

Views: 1550

Answers (1)

Mark Heath
Mark Heath

Reputation: 49482

You need to rewind the memory stream back to the beginning

ms.Position = 0

Upvotes: 3

Related Questions