如何从 C# 中的在线资源播放 .mp3 文件?

Ale*_*oci 1 c# mp3 winforms

我的问题与这个问题非常相似

我有音乐网址。网址如http://site.com/audio.mp3。我想在线播放这个文件,比如 youtube。你知道一个类或代码可以做到这一点吗?

如何在不下载所有内容的情况下在线播放 mp3?

播放文件缓存将被创建但至少立即播放文件

Ale*_*oci 5

我找到了图书馆 NAudio http://naudio.codeplex.com/的解决方案

解决方案

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);
                }
            }
        }
    }
}`
Run Code Online (Sandbox Code Playgroud)

我在这里找到了答案 使用 C# 从流中播放音频