我正在努力从网址源传播mp3几天。除了一个小问题,它几乎可以正常工作。问题是播放mp3时会出现一些短暂的中断。我无法弄清楚为什么会这样。我需要帮助,我的代码就是这样。对不起,它太长了,但也许你想试试。
enter code here
private void buttonPlay_Click(object sender,EventArgs e) {
string url = "http://freedownloads.last.fm/download/569264057/Get%2BGot.mp3";
bool playingStarted = false;
WaveStream str;
WaveFormat format = GetWaveFormat(url);
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
int contentLength=(int)resp.ContentLength;
Stream stream = resp.GetResponseStream();
BufferedWaveProvider provider = new BufferedWaveProvider(format);
provider.BufferDuration = TimeSpan.FromMinutes(20);
byte[] buffer = new byte[format.SampleRate];
byte[] totalBuffer = new byte[contentLength];
byte[] mp3StreamBuffer = new byte[format.SampleRate];
int bytesRead = 0, totalBytes=0;
int decBytes = 0;
long skipTo = 0;
Task.Factory.StartNew(() =>
{
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
Buffer.BlockCopy(buffer, 0, totalBuffer, totalBytes, bytesRead);
totalBytes += bytesRead;
this.Invoke((MethodInvoker)delegate { progressBar2.Value = (int)(totalBytes * 100.0 / contentLength); });
if (totalBytes < format.AverageBytesPerSecond)
continue;
str = new Mp3FileReader(new MemoryStream(totalBuffer));
str.Position = skipTo;
while ((decBytes = str.Read(mp3StreamBuffer, 0, mp3StreamBuffer.Length)) > 0)
{
provider.AddSamples(mp3StreamBuffer, 0, decBytes);
}
skipTo = str.Position;
if (playingStarted)
{
playingStarted = false;
Task.Factory.StartNew(() =>
{
play.Init(provider);
play.Play();
});
}
}
});
}
WaveFormat GetWaveFormat(string url)
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Stream stream = resp.GetResponseStream();
byte[] buffer = new byte[2048];
int readBytes = 0, bytesReceived = 0;
MemoryStream ms = new MemoryStream();
while ((readBytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, readBytes);
bytesReceived += readBytes;
if (bytesReceived >= 10000) break;
}
req.Abort();
resp.Close(); ms.Position = 0;
WaveStream tempStream = new Mp3FileReader(ms);
return tempStream.WaveFormat;
}