我正在寻找使这段代码线程安全的解决方案:
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
,是吗?任何使其线程安全的解决方案?
此外,如果流是无尽的或非常大的,如何清除已播放的流部分?
答案 0 :(得分:1)
有一个从NAudio源代码中的URL流式传输MP3的示例(查看MP3 streaming demo中的NAudioDemo项目)。我推荐的方法是在将每个MP3帧解码为PCM后,将BufferedWaveProvider
填入音频。