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; }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)