Quantcast
Channel: naudio Work Item Rss Feed
Viewing all articles
Browse latest Browse all 738

Commented Unassigned: Create WAV stream in memory [16503]

$
0
0
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
Comments: as I said on stack overflow, you need to reset the position of your memorystream to 0

Viewing all articles
Browse latest Browse all 738

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>