Alessio Koci
Alessio Koci

Reputation: 1113

How to play .mp3 file from online resources in C#?

my question is very similar to this question

I have music urls. Urls like http://site.com/audio.mp3 . I want play this file online, like youtube. Do you know a class or code can do this ?

How can I play an mp3 online without downloading all for to play it?

to play the file cache will be created but at least play the file immediately

Upvotes: 1

Views: 9756

Answers (2)

Alessio Koci
Alessio Koci

Reputation: 1113

I found the solution with the library NAudio http://naudio.codeplex.com/

SOLUTION

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);
                }
            }
        }
    }
}`

I FOUND THE ANSWER HERE Play audio from a stream using C#

Upvotes: 5

Vaughan Hilts
Vaughan Hilts

Reputation: 2879

Many libraries like IrKlang provide streaming audio support, if you're looking for minimal development effort I'd suggest you take a look at it!

http://www.ambiera.com/irrklang/

Upvotes: 1

Related Questions