Search code examples
c#winformsmp3

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


Solution

  • 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#