在 C# 中是否有一种方法可以直接从 System.IO.Stream 例如从 WebRequest 返回而不将数据临时保存到磁盘?
Is there a way in C# to play audio (for example, MP3) direcly from a System.IO.Stream that for instance was returend from a WebRequest without saving the data temporarily to the disk?
在 NAudio 1.3 的帮助下,可以:
With the help of NAudio 1.3 it is possible to:
如果能够播放一半加载的 MP3 文件就太好了,但由于 NAudio 库设计.
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.
这是完成工作的函数:
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); } } } } } 推荐答案更新答案以反映 NAudio 最新版本的变化
可以使用我编写的 NAudio 开源 .NET 音频库.它会在您的 PC 上寻找 ACM 编解码器来进行转换.NAudio 提供的 Mp3FileReader 当前期望能够在源流中重新定位(它预先构建 MP3 帧的索引),因此它不适合通过网络进行流式传输.但是,您仍然可以使用 NAudio 中的 MP3Frame 和 AcmMp3FrameDecompressor 类来动态解压缩流式 MP3.
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. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame and AcmMp3FrameDecompressor classes in NAudio to decompress streamed MP3 on the fly.
我在我的博客上发布了一篇文章,解释了 如何使用 NAudio 播放 MP3 流.本质上,您有一个线程下载 MP3 帧,解压缩它们并将它们存储在 BufferedWaveProvider 中.然后另一个线程使用 BufferedWaveProvider 作为输入进行回放.
I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider. Another thread then plays back using the BufferedWaveProvider as an input.
更多推荐
使用 C# 从流中播放音频
发布评论