我正在寻找使此代码线程安全的解决方案:
private Stream ms = new MemoryStream();
public void PlayMp3FromUrl(string url)
{
new Thread(delegate(object o)
{
var response = WebRequest.Create(url).GetResponse();
using (var stream = response.GetResponseStream())
{
byte[] buffer = new byte[65536]; // 64KB chunks
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
var pos = ms.Position;
ms.Position = ms.Length;
ms.Write(buffer, 0, read);
ms.Position = pos;
}
}
}).Start();
// Pre-buffering some data to allow NAudio to start playing
while (ms.Length < 65536*10)
Thread.Sleep(1000);
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播放时,不能将ms.Position
更改为ms.Write
,是吗?有什么解决方案可以确保线程安全?
还有如果流是无穷的或者很大,如何清除已经播放的流部分?
在NAudio源代码中有一个从URL流式传输MP3的示例(在NAudioDemo项目中查看MP3流式传输演示)。我推荐的方法是在将每个MP3帧解码为PCM后,在BufferedWaveProvider
中填充接收到的音频。