views:

21682

answers:

10

Is there a way in C# to play audio (e.g. MP3) direcly from a Stream (I mean the real .NET class) that for instance was returend from a WebRequest without saving the data temporarily to the disk?


Solution with NAudio

With the help of NAudio 1.3 it is possible to:

  1. load a mp3 file from a url into a MemoryStream
  2. convert mp3 data into wave data after it was completely loaded
  3. playback the wave data using the NAudios WaveOut class

It would have been nice to be able to even play a half loaded mp3 file but this seems to be impossible due to the NAudio library design.

And this is the function that will do the work:

    public static void PlayMp3FromUrl(string url)
    {
        using (Stream ms = new MemoryStream())
        {
            using (Stream stream = WebRequest.Create(url)
                .GetResponse().GetResponseStream())
            {
                byte[] buffer = new byte[32768];
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
            }

            ms.Position = 0;
            using (WaveStream blockAlignedStream =
                new BlockAlignReductionStream(
                    WaveFormatConversionStream.CreatePcmStream(
                        new Mp3FileReader(ms))))
            {
                using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                {
                    waveOut.Init(blockAlignedStream);
                    waveOut.Play();                        
                    while (waveOut.PlaybackState == PlaybackState.Playing )                        
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
        }
    }
+2  A: 

The SoundPlayer class can do this. It looks like all you have to do is set its Stream property to the stream, then call Play.

edit
I don't think it can play MP3 files though; it seems limited to .wav. I'm not certain if there's anything in the framework that can play an MP3 file directly. Everything I find about that involves either using a WMP control or interacting with DirectX.

OwenP
I've been trying to find a .NET library that does MP3 encoding and decoding for years now, but I don't think it exists.
MusiGenesis
NAudio should do the job for you - at least for decodeing (see first post)
Martin
SoundPlayer has nasty issues with GC and will randomly play garbage unless you use the official Microsoft workaround (click Workarounds): http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=93642
romkyns
+15  A: 

It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion, which is not ideal really, but it works for the few MP3s I've tried it with. Here's an example from the NAudioDemo app...

WaveStream mp3Reader = new Mp3FileReader(fileName);
WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);

I haven't put a constructor that takes a stream on the Mp3FileReader class, but it would be a very easy change to make.

Mark Heath
+1  A: 

NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.

Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.

MusiGenesis
+3  A: 

Bass can do just this, (www.un4seen.com -> bass -> bass.net) Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play assoon as you have enough data to start the playback..

A: 

I've written a .NET library in C# as a wrapper to MCI (Multimedia Controller Interface) P/Invokes, if someone needs it, leave me a comment I will send both the code and assembly.

milot
I think that MCI is unable to do anything directly out of a MemoryStream what doesn't even makes it a half solution for this problem like NAudio does.
Martin
A: 

I haven't tryed it from a WebRequest, but both the Windows Media Player activex and the MediaElement (from WPF) components are capable of playing and buffering mp3 streams.

I use it to play data coming from a shoutcast stream and it worked great, however, I'm not sure if it will work on the scenario you propose.

Ramiro Berrelleza
A: 

But what about modified Mp3FileReader.cs class that can accept streams? Where can we get it?

Laserson
NAudio 1.3 is able to accept streams without modifications. I updated my solution.
Martin
A: 

I've always used FMOD for things like this because it's free for non-commercial use and works well.

That said, I'd gladly switch to something that's smaller (FMOD is ~300k) and open-source. Super bonus points if it's fully managed so that I can compile / merge it with my .exe and not have to take extra care to get portability to other platforms...

(FMOD does portability too but you'd obviously need different binaries for different platforms)

romkyns
A: 

I got some help here,while my problem doesn't leave.I am now trying to read the sound files(of course the same style) into a specific stream so that I can make a buffer before the go.I just wonder if there is a way to read just partuliar period of the song or sound to the stream.If there is,let me konw,and thanks

qujianjun
A: 

I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

http://sourceforge.net/projects/mpg123net/

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

Daniel Mošmondor
Great! I look forward to taking a look at it this weekend.
Larry Smithmier