从URL读取音频并保存

时间:2018-06-13 04:42:48

标签: c# asp.net naudio

下面给出的代码是从URL播放音频。是否可以从该URL读取流并创建音频文件并保存在PC中?

var url = "http://media.ch9.ms/455884123cf7a0852876.wav";
using(var mf = new MediaFoundationReader(url))
using(var wo = new WaveOutEvent())
{
    wo.Init(mf);
    wo.Play();
    while (wo.PlaybackState == PlaybackState.Playing)
    {
        Thread.Sleep(1000);
    }
}

1 个答案:

答案 0 :(得分:0)

我使用以下代码来做到这一点:

static void Main(string[] args)
    {
        var url = "fake-url";
        using (var mf = new CustomWaveOutEvent(url))
        using (var wo = new WaveOutEvent())
        {
            wo.Init(mf);
            wo.Play();
            while (wo.PlaybackState == PlaybackState.Playing)
            {
                Thread.Sleep(1000);
            }
        }
    }

CustomWaveOutEvent类为:

public class CustomWaveOutEvent : MediaFoundationReader
{
    private WaveFileWriter fileStream;

    public CustomWaveOutEvent(string file) : base(file)
    {
        fileStream = new WaveFileWriter("OutputFile.wav", this.WaveFormat);
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        var dataToReturn = base.Read(buffer, offset, count);

        fileStream.Write(buffer);

        return dataToReturn;
    }
}

希望能对您有所帮助