Opening an audio (wav) file from a MemoryStream to determine the duration

Is there a way, either within the Framework, or using P / Invoke to determine the duration of a wav file stored in a MemoryStream?

I already looked at Managed DirectX and another similar question , but everything seems to work with paths and not provide any way to stream the stream. One of the links in the question I was referring to ( Simple C # Wave Editor ....) gives a fairly clear idea that I can parse a MemoryStream to determine the length of the wav file. Ideally, I would not reinvent the wheel.

+4
source share
3 answers

I agree with Alex. I took the time to put together a small program with three lines of code that print the duration of the wav file.

  var stream=new MemoryStream(File.ReadAllBytes("test.wav")); var wave = new WaveFileReader(stream); Console.WriteLine(wave.TotalTime); // wave.TotalTime -> TimeSpan 

Download the NAudio library: you will find NAudio.dll in the package.

Just specify the NAudio.dll file in your project.

At the time of writing release 1.3.

As the author says in his blog, WaveFileReader accepts Stream ; not just the file path.

Remember that version 1.3 is built for x86. If you want it to work on x64, you need to force your project on x86. If you want NAudio.dll for x64 (for example, me), you need to recompile "any processor". For me, both solutions worked like a charm.

+6
source

Try a calculation

streamSize == headerSizeIfAny + playTime * fetch * singleSampleSize โ†’

playTime = (streamSize [in bytes] - headerSizeIfAny) / (sample [samples per second] * singleSampleSize [byte])

0
source

Check this:

http://www.sonicspot.com/guide/wavefiles.html

and this one

 typedef struct { WORD wFormatTag; WORD nChannels; DWORD nSamplesPerSec; DWORD nAvgBytesPerSec; WORD nBlockAlign; WORD wBitsPerSample; WORD cbSize;} WAVEFORMATEX; 

So you have your memystream ... Look for 0x10 (to skip the Riff header) + 0x08 (for the format header) = 24

And you are in the structure above.

Use stream.ReadInt16() and stream.ReadInt32() to read the required structure elements.

Then find 54, read one DWORD and that many bytes are your sample data.

Then derive your duration from these variables.

NOTE: this will only work for the ONLY STRONG PCM wave files stored in your memory stream. For others, you must follow the headers and properly disassemble them, find the data block and calculate the duration according to this size.

0
source

All Articles