Home > Net >  How to use MP3Sharp with IFormFile
How to use MP3Sharp with IFormFile

Time:12-14

I want to convert an mp3 file to pcm using MP3Sharp (https://github.com/ZaneDubya/MP3Sharp) in a web app, where the mp3 file is passed in as IFormFile

It works if I save the file to disk first like this ...

                using (Stream fileStream = new FileStream("file.mp3", FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                MP3Stream stream = new MP3Stream("file.mp3");

... but when I try to do it as a stream without writing to file it doesn't work:

                using (var fileStream = new MemoryStream())
                {
                    await file.CopyToAsync(fileStream);
                    MP3Stream stream = new MP3Stream(fileStream);
                }

The MP3Stream constructor throws this exception:

MP3Sharp.MP3SharpException: 'Unhandled channel count rep: -1 (allowed values are 1-mono and 2-stereo).'

... Any ideas on what I'm doing wrong?

CodePudding user response:

After your code does file.CopyToAsync(fileStream), the MemoryStream's read/write position is pointing after the written MP3 data at the end of the MemoryStream.

The MP3Stream then trying to read from the MemoryStream will only notice that the end of the MemoryStream has been reached (because its read/write position is already at the end) and throws an exception.[1]

Thus, after copying the MP3 data into the MemoryStream, set the MemoryStream's read/write position back to where it was before you copied the MP3 data into it (in the case of your example code it's the beginning of the MemoryStream, position 0):

await file.CopyToAsync(fileStream);
fileStream.Position = 0;

Side note: Like FileStream and MemoryStream, MP3Stream is also a Stream and therefore an IDisposable, too. And like you already did with the FileStream and the MemoryStream, you should use the using statement for the MP3Stream as well.


[1] The exception you got from the MP3Sharp library is misleading, and as such is kind of a bug in the library. Because, when attempting to read a byte from a stream and the stream is at its end, the Stream.ReadByte method will return -1 to indicate end-of-stream. And as apparent by the exception message, it seems the MP3Sharp library does not properly treat the -1 value here as simply meaning "the end of the stream has been reached and no (further) data could be read" and misinterprets it as a channel count value.

  • Related