protected override void RipLoop(Domain.BufferedStream bufferedStream)
        {
            _currentFrame = Mp3Frame.LoadFromStream(bufferedStream);

            if (_currentFrame == null)
            {
                throw new RipFailedException($"Failed to stream from '{CurrentStreamSource.StreamUrl}. The stream is either down or not a MP3 compatible stream.");
            }

            if (_decompressor == null)
            {
                // don't think these details matter too much - just help ACM select the right codec
                // however, the buffered provider doesn't know what sample rate it is working at
                // until we have a frame
                _waveFormat = new Mp3WaveFormat(
                    _currentFrame.SampleRate,
                    _currentFrame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                    _currentFrame.FrameLength,
                    _currentFrame.BitRate
                    );

                _decompressor = new AcmMp3FrameDecompressor(_waveFormat);
                //var appSetting = AppSettings.Current;

                //if(appSetting.RecordBacktrackSeconds > 0) {
                //    // ms per frame = (samples per frame / sample rate(in hz)) * 1000
                //    var backFrameStackSize = (appSetting.RecordBacktrackSeconds * 1000) / (((float)_currentFrame.SampleCount / (float)_currentFrame.SampleRate) * 1000);
                //    BackFrames = new PipeQueue<FrameDecompressedEventArgs<Mp3Frame>>((int)Math.Ceiling(backFrameStackSize));
                //}
            }

            int decompressed = _decompressor.DecompressFrame(_currentFrame, _buffer, 0);

            RaiseFrameDecompressed(_currentFrame, _waveFormat, _decompressor.OutputFormat, _buffer, decompressed);
        }
Example #2
0
        /// <summary>
        /// Reads decompressed PCM data from our MP3 file.
        /// </summary>
        public override int Read(byte[] sampleBuffer, int offset, int numBytes)
        {
            int bytesRead = 0;

            lock (repositionLock)
            {
                if (decompressLeftovers != 0)
                {
                    int toCopy = Math.Min(decompressLeftovers, numBytes);
                    Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
                    decompressLeftovers -= toCopy;
                    if (decompressLeftovers == 0)
                    {
                        decompressBufferOffset = 0;
                    }
                    else
                    {
                        decompressBufferOffset += toCopy;
                    }
                    bytesRead += toCopy;
                    offset    += toCopy;
                }

                while (bytesRead < numBytes)
                {
                    Mp3Frame frame = ReadNextFrame();
                    if (frame != null)
                    {
                        if (repositionedFlag)
                        {
                            decompressor.Reset();
                            repositionedFlag = false;
                        }
                        int decompressed = decompressor.DecompressFrame(frame, decompressBuffer, 0);

                        int toCopy = Math.Min(decompressed, numBytes - bytesRead);
                        Array.Copy(decompressBuffer, 0, sampleBuffer, offset, toCopy);
                        if (toCopy < decompressed)
                        {
                            decompressBufferOffset = toCopy;
                            decompressLeftovers    = decompressed - toCopy;
                        }
                        else
                        {
                            // no lefovers
                            decompressBufferOffset = 0;
                            decompressLeftovers    = 0;
                        }
                        offset    += toCopy;
                        bytesRead += toCopy;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Debug.Assert(bytesRead <= numBytes, "MP3 File Reader read too much");
            return(bytesRead);
        }
Example #3
0
        public async Task StreamEpisodeAsync(Episode current)
        {
            var memoryStream = new MemoryStream();

            var mp3Stream      = await new HttpClient().GetStreamAsync(current.EpisodeUri);
            var mp3ChunkBuffer = new byte[4];                                                             //hier kommen unsere 4 bytes immer rein :D

            using (var fileStream = new FileStream(current.LocalPath, FileMode.Create, FileAccess.Write)) //und der crap muss ja auch gespeichert werden
            {
                while (mp3Stream.Read(mp3ChunkBuffer, 0, 4) > 0)                                          //4er bytes lesen bis nix mehr kommt (falls du skippen musst, vergiss nicht den geskipten part auch in die file zu schreiben)
                {
                    memoryStream.Write(mp3ChunkBuffer, 0, mp3ChunkBuffer.Length);
                    fileStream.Write(mp3ChunkBuffer, 0, mp3ChunkBuffer.Length); //schreib den chunck in die datei
                }
            }

            mp3Stream.Close();

            var readFullyStream = new ReadFullyStream(memoryStream);
            var frame           = Mp3Frame.LoadFromStream(readFullyStream);
            IMp3FrameDecompressor decompressor         = CreateFrameDecompressor(frame);
            BufferedWaveProvider  bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);

            bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20);

            var buffer       = new byte[16384 * 4];
            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);

            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
        }
Example #4
0
        public void Play()
        {
            byte[] buffer = new byte[RequestConstants.DepressLength]; //[16384 * 4]; // needs to be big enough to hold a decompressed frame
            while (true)
            {
                while (RStream.Length == 0 && (IsPlaying || RStream.Length > PlayNotifySize))
                {
                    IsPlaying = true;
                    //播放流程待优化
                    Mp3Frame frame = null;
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                    {
                        Thread.Sleep(500);
                        continue;
                    }

                    try
                    {
                        RStream.Position = PlayPosition;
                        frame            = Mp3Frame.LoadFromStream(RStream);
                        PlayPosition    += frame.FrameLength;
                        Parent.Log.WriteLog(string.Format("目标播放至{0},{1}", PlayPosition, DateTime.Now.ToString()));
                        if (frame == null)
                        {
                            //出现错误
                            IsPlaying = false;
                            throw new NotImplementedException();
                        }
                    }
                    catch (Exception)
                    {
                        Parent.Log.WriteLog("缓冲中");
                        IsPlaying = false;
                        break;
                    }

                    if (decompressor == null)
                    {
                        WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                        decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                        bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                        _waveOut.Init(bufferedWaveProvider);
                        _waveOut.Play();
                    }
                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                    bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                }
                if (Stopped)
                {
                    RStream = new MemoryStream();
                    break;
                }
                Thread.Sleep(200);
            }
        }
        private void ReadFromStream()
        {
            IMp3FrameDecompressor Decompressor = null;

            try
            {
                do
                {
                    if (IsBufferNearlyFull)
                    {
                        Thread.Sleep(500);
                    }
                    else
                    {
                        Mp3Frame Frame;

                        try
                        {
                            Frame = Mp3Frame.LoadFromStream(m_ASound.MP3.RFullyStream);
                        }
                        catch (EndOfStreamException)
                        {
                            m_ASound.FullyStreamed = true;
                            break;
                        }

                        if (Decompressor == null)
                        {
                            Decompressor         = CreateFrameDecompressor(Frame);
                            m_ASound.WavProvider = new BufferedWaveProvider(Decompressor.OutputFormat);
                            m_ASound.WavProvider.BufferDuration = TimeSpan.FromSeconds(30);
                        }

                        int Decompressed = Decompressor.DecompressFrame(Frame, m_Buffer, 0);
                        m_ASound.WavProvider.AddSamples(m_Buffer, 0, Decompressed);
                    }
                } while (m_PlaybackState != StreamingPlaybackState.Stopped);
            }
            finally
            {
                if (Decompressor != null)
                {
                    Decompressor.Dispose();
                }
            }
        }
Example #6
0
        private int DecompressFrame(Mp3Frame frame, byte[] buffer)
        {
            // decode frame
            if (_decompressor == null)
            {
                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                _decompressor = new AcmMp3FrameDecompressor(waveFormat);

                _waveProvider = new BufferedWaveProvider(_decompressor.OutputFormat);
                _waveProvider.BufferDuration = TimeSpan.FromSeconds(5);

                _channels = _waveProvider.WaveFormat.Channels;

                _sampleProvider = _waveProvider.ToSampleProvider();
            }

            return(_decompressor.DecompressFrame(frame, buffer, 0));
        }
Example #7
0
        private void PublishFromStream()
        {
            while (!_tokenSource.IsCancellationRequested)
            {
                var frame = Mp3Frame.LoadFromStream(_stream);
                if (_decompressor == null)
                {
                    _decompressor = CreateFrameDecompressor(frame);
                }
                var bytesRead = _decompressor.DecompressFrame(frame, _buffer, 0);
                if (bytesRead == 0)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    continue;
                }
                AddSamples(_buffer, 0, bytesRead);
#if DEBUG
                Trace.WriteLine($"Buffered '{Source}' ({BufferedStream.CurrentWriteTime})...");
#endif
            }
#if DEBUG
            Trace.WriteLine($"Stopped reading from '{Source}' ({BufferedStream.CurrentWriteTime}).");
#endif
        }
Example #8
0
        private void StreamMp3(object state)
        {
            if (Settings.IgnoreSSLcertificateError)
            {
                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
                }
                else
                {
                    ServicePointManager.ServerCertificateValidationCallback = null;
                }
            }

            _fullyDownloaded = false;
            var url = (string)state;

            _webRequest           = (HttpWebRequest)WebRequest.Create(url);
            _webRequest.KeepAlive = true;
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)_webRequest.GetResponse();
            }
            catch (WebException)
            {
                return;
            }
            var buffer = new byte[16384 * Settings.NetworkBuffer]; // needs to be big enough to hold a decompressed frame

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (Stream responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else if (!_fullyDownloaded)
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                Debug.WriteLine("fullyDownloaded!");
                                _fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException)
                            {
                                Debug.WriteLine("WebException!");
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                decompressor          = CreateFrameDecompressor(frame);
                                _bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                _bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(Settings.NetworkBuffer);
                                // allow us to get well ahead of ourselves
                            }
                            try
                            {
                                int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                                _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                            }
                            catch (ArgumentNullException)
                            {
                                Debug.WriteLine("fullyDownloaded!");
                                _fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch
                            {
                                //oops
                            }
                        }
                    } while (_playbackState != StreamingPlaybackState.Stopped);
                    Debug.WriteLine("Exiting");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    if (decompressor != null)
                    {
                        decompressor.Dispose();
                    }
                    readFullyStream.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
                //StopPlayback();
            }
        }
Example #9
0
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            var url = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    /// TODO: Update this to show an error message and handle it properly
                    //textdebug.Text = e.Message;
                }
                return;
            }

            var buffer = new byte[16384 * 4];

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;
                                break;
                            }
                            catch (WebException)
                            {
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                //this.bufferedWaveProvider.BufferedDuration = 250;
                            }
                            /// TODO: Sometimes this throws MMException
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Example #10
0
        private void PlayStream(Stream responseStream, CancellationToken cancelToken, byte[] buffer, IMp3FrameDecompressor decompressor = null)
        {
            var readFullyStream = new ReadFullyStream(responseStream);

            while (!cancelToken.IsCancellationRequested)
            {
                if (IsBufferNearlyFull)
                {
                    Console.WriteLine("Buffer getting full, taking a break");
                    Thread.Sleep(500);
                }
                else
                {
                    Mp3Frame frame;
                    try
                    {
                        frame = Mp3Frame.LoadFromStream(readFullyStream);
                    }
                    catch (EndOfStreamException)
                    {
                        var fullyDownloaded = true;
                        // reached the end of the MP3 file / stream
                        break;
                    }
                    catch (WebException)
                    {
                        // probably we have aborted download from the GUI thread
                        break;
                    }
                    if (frame == null)
                    {
                        break;
                    }
                    if (decompressor == null)
                    {
                        // don't think these details matter too much - just help ACM select the right codec
                        // however, the buffered provider doesn't know what sample rate it is working at
                        // until we have a frame
                        decompressor         = CreateFrameDecompressor(frame);
                        bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                        bufferedWaveProvider.BufferDuration =
                            TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                                      //this.bufferedWaveProvider.BufferedDuration = 250;
                    }
                    try
                    {
                        int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                        if (bufferedWaveProvider != null)
                        {
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    }
                    catch (Exception)
                    {
                    }

                    //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                }

                if (waveOut == null && bufferedWaveProvider != null)
                {
                    waveOut = new WaveOut();

                    volumeProvider        = new VolumeWaveProvider16(bufferedWaveProvider);
                    volumeProvider.Volume = 1.0f;
                    waveOut.Init(volumeProvider);
                    waveOut.Volume = volume;
                    waveOut.Play();
                }
            }
        }
Example #11
0
        private static void StreamMp3(object state)
        {
            FullyDownloaded = false;
            var url = (Uri)state;

            _webRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)_webRequest.GetResponse();
            }
            catch (WebException e)
            {
                OnPlaybackError?.Invoke(_webRequest, e);
                return;
            }
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            //Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                            continue;
                        }
                        Mp3Frame frame;
                        try
                        {
                            frame = Mp3Frame.LoadFromStream(readFullyStream);
                        }
                        catch (EndOfStreamException)
                        {
                            FullyDownloaded = true;
                            // reached the end of the MP3 file / stream
                            break;
                        }
                        catch (WebException)
                        {
                            // probably we have aborted download from the GUI thread
                            break;
                        }
                        if (decompressor == null)
                        {
                            // don't think these details matter too much - just help ACM select the right codec
                            // however, the buffered provider doesn't know what sample rate it is working at
                            // until we have a frame
                            decompressor          = CreateFrameDecompressor(frame);
                            _bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat)
                            {
                                BufferDuration = TimeSpan.FromSeconds(60)
                            };
                            // allow us to get well ahead of ourselves
                            //this._bufferedWaveProvider.BufferedDuration = 250;
                        }
                        if (frame == null)
                        {
                            FullyDownloaded = true;
                            break;
                        }

                        int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                        //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                        _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                    } while (PlaybackState != StreamingPlaybackState.Stopped);
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor?.Dispose();
                }
            }
            finally
            {
                decompressor?.Dispose();
            }
        }
Example #12
0
        //------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Provides a pcm stream that can be used to a waveout device (i.e. speakers)
        /// or can write pcm samples to a System.IO.Stream
        /// </summary>
        public void Start()
        {
            //declares
            IMp3FrameDecompressor decompressor = null;
            HttpWebResponse       resp         = null;

            IsActive = true;

            //init state to buffering
            playbackState = StreamingPlaybackState.Buffering;

            //do web request
            var webRequest = (HttpWebRequest)WebRequest.Create(this.mp3url);

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex);
            }
            if (resp == null)
            {
                return;
            }

            //local buffer that is overriden each  time a mp3 frame is decompressed
            var buffer          = new byte[16384 * 4];
            var respStream      = resp.GetResponseStream();
            var readFullyStream = new ReadFullyStream(respStream);

            //Streaming Loop
            try
            {
                while (playbackState != StreamingPlaybackState.Stopped)
                {
                    //get frame
                    Mp3Frame frame;
                    try
                    {
                        frame = Mp3Frame.LoadFromStream(readFullyStream);
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceError(ex.Message);
                        break;
                    }

                    //get the codec info from the first frame
                    if (decompressor == null)
                    {
                        decompressor = Tools.CreateFrameDecompressor(frame);
                        audioFormat  = new AudioFormat(decompressor.OutputFormat.SampleRate, (ushort)decompressor.OutputFormat.BitsPerSample, (ushort)decompressor.OutputFormat.Channels);
                        if (OnPCMStart != null)
                        {
                            OnPCMStart(this, decompressor.OutputFormat);
                        }
                    }

                    //write decompressed (pcm) samples to local buffer
                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                    if (IsActive)
                    {
                        //fire event
                        if (OnAudioDataCaptured != null)
                        {
                            OnAudioDataCaptured(this, new AudioEventArgs(buffer, decompressed));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugEx.TraceError(ex.Message);
            }
        }
Example #13
0
        private async Task DecompressFrames()
        {
            byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
            do
            {
                try
                {
                    //WaveBuffer getting full, taking a break
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 2)
                    {
                        await Task.Delay(500);
                    }
                    //StreamBuffer empty, taking a break
                    else if (stream.Length < 16384 * 2)
                    {
                        await Task.Delay(500);
                    }
                    else
                    {
                        Mp3Frame frame = Mp3Frame.LoadFromStream(stream);
                        if (frame == null)
                        {
                            continue;
                        }
                        if (decompressor == null)
                        {
                            WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                            decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                            bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                            bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(5); // allow us to get well ahead of ourselves
                        }

                        try
                        {
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            if (decompressed > 0)
                            {
                                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                            }
                        }
                        catch (NAudio.MmException)
                        { }

                        if (waveOut == null)
                        {
                            waveOut = new WaveOut();
                            VolumeWaveProvider16 volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);
                            volumeProvider.Volume = 1.0f;
                            waveOut.Init(volumeProvider);
                            waveOut.Play();
                        }
                    }
                }
                catch (EndOfStreamException)
                {
                    CleanUpAudio();
                }
            } while (IsPlaying);

            CleanUpAudio();
        }
Example #14
0
        public static void receivingSong()
        {
            waveOut = new WaveOut();
            decomp  = null;

            int count  = 0;
            var buffer = new byte[16384 * 4];

            // then receive data
            do
            {
                //if(bufferedWaveProvider != null &&
                //        bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes
                //      < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                if (bufferedWaveProvider != null && bufferedWaveProvider.BufferedDuration.TotalSeconds > 10)
                {
                    Thread.Sleep(1000);
                }
                var receivedData = client.Receive(ref ep);

                if (Encoding.ASCII.GetString(receivedData) == "done")
                {
                    break;
                }
                else
                {
                    client.Send(Encoding.ASCII.GetBytes("more"), 4);
                }

                Mp3Frame frame;
                Stream   ms = new MemoryStream();

                ms.Write(receivedData, 0, receivedData.Length);
                ms.Position = 0;
                frame       = Mp3Frame.LoadFromStream(ms, true);
                if (decomp == null)
                {
                    WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                              frame.FrameLength, frame.BitRate);
                    decomp = new AcmMp3FrameDecompressor(waveFormat);
                    bufferedWaveProvider = new BufferedWaveProvider(decomp.OutputFormat);
                    bufferedWaveProvider.BufferDuration =
                        TimeSpan.FromSeconds(20);
                    //var volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);
                    //volumeProvider.Volume = 1;

                    // allow us to get well ahead of ourselves
                    //this.bufferedWaveProvider.BufferedDuration = 250;
                }
                if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 5 && waveOut.PlaybackState == PlaybackState.Stopped && buffering == true)
                {
                    waveOut.Init(bufferedWaveProvider);
                    waveOut.Play();
                    //ThreadStart play = new ThreadStart(playSong);
                    //Thread playThread = new Thread(play);
                    //playThread.Start();
                }
                int decompressed = decomp.DecompressFrame(frame, buffer, 0);
                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);



                count++;
            } while (buffering);
        }
Example #15
0
        public void StarReceive()
        {
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            IMp3FrameDecompressor decompressor = null;

            new Thread(() =>
            {
                try
                {
                    using (var responseStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var readFullyStream = new ReadFullyStream(responseStream);
                        do
                        {
                            if (IsBufferNearlyFull)
                            {
                                Console.WriteLine("缓冲区满了,休息一下");
                                Thread.Sleep(500);
                            }
                            else
                            {
                                Mp3Frame frame;
                                try
                                {
                                    frame = Mp3Frame.LoadFromStream(readFullyStream, true);
                                }
                                catch (EndOfStreamException ex)
                                {
                                    //fullyDownloaded = true;
                                    //已到达MP3文件/流的结尾
                                    continue;
                                }
                                if (frame == null)
                                {
                                    break;
                                }
                                if (decompressor == null)
                                {
                                    // 不要认为这些细节太重要-只要帮助ACM选择正确的编解码器
                                    // 但是,缓冲提供程序不知道它的采样率是多少
                                    // 直到我们有了一个框架
                                    decompressor         = CreateFrameDecompressor(frame);
                                    bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                    bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // 设置缓冲区20秒大小
                                }
                                int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                //Console.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                            }
                            Thread.Sleep(1);
                        } while (true);
                    }
                }
                finally
                {
                    if (decompressor != null)
                    {
                        decompressor.Dispose();
                    }
                }
            })
            {
                IsBackground = true
            }.Start();
        }
Example #16
0
        private void StreamMp3(object state)
        {
            // Store that we don't have the stream downloaded
            FullyDownloaded = false;
            // Store the URL
            string URL = (string)state;

            // Create the web request
            Request = (HttpWebRequest)WebRequest.Create(URL);
            // Create a variable for the response
            HttpWebResponse Response;

            // Try to make the web request
            try
            {
                Response = (HttpWebResponse)Request.GetResponse();
            }
            // If there is an exception, just return
            catch (WebException)
            {
                return;
            }

            // Create a place to store the buffer data (needs to be big enough to hold a decompressed frame)
            byte[] Buffer = new byte[16384 * 4];

            // Remove the Decompressor
            IMp3FrameDecompressor Decompressor = null;

            // Start processing the data
            try
            {
                // Get the response stream
                using (Stream ResponseStream = Response.GetResponseStream())
                {
                    // Store as a ready stream
                    FullStream ReadyStream = new FullStream(ResponseStream);
                    // And start working with it
                    do
                    {
                        // If the buffer is nearly full
                        if (IsBufferNearlyFull)
                        {
                            // Sleep for half a second
                            Thread.Sleep(500);
                        }
                        else
                        {
                            // Set a place to store the frame
                            Mp3Frame Frame;
                            // Try to create the frame from the stream that is ready
                            try
                            {
                                Frame = Mp3Frame.LoadFromStream(ReadyStream);
                            }
                            // If we reach the end of the stream, break the do
                            catch (EndOfStreamException)
                            {
                                FullyDownloaded = true;
                                break;
                            }
                            // If we get a web exception, break the do
                            // Original Message: Probably we have aborted download from the GUI thread
                            catch (WebException)
                            {
                                break;
                            }
                            // If there is no frame, break the do
                            if (Frame == null)
                            {
                                break;
                            }
                            // If there is no decompressor:
                            if (Decompressor == null)
                            {
                                // Don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                Decompressor = CreateFrameDecompressor(Frame);
                                // Create a new wave provider
                                WaveProvider = new BufferedWaveProvider(Decompressor.OutputFormat)
                                {
                                    BufferDuration = TimeSpan.FromSeconds(20) // Allow us to get well ahead of ourselves
                                };
                            }
                            // Decompress a single frame
                            int Decompressed = Decompressor.DecompressFrame(Frame, Buffer, 0);
                            // And add it to the buffer (TODO: Confirm if my explanations are correct)
                            WaveProvider.AddSamples(Buffer, 0, Decompressed);
                        }
                    } while (State != StreamingState.Stopped);
                    // Finally, dispose the decompressor
                    Decompressor.Dispose();
                }
            }
            finally
            {
                // If the decompressor is not empty, dispose it
                if (Decompressor != null)
                {
                    Decompressor.Dispose();
                }
            }
        }
Example #17
0
        private void StreamMp3()
        {
            _fullyDownloaded = false;
            IMp3FrameDecompressor deCompressor = null;

            try
            {
                do
                {
                    if (IsBufferNearlyFull)
                    {
                        Debug.WriteLine("Buffer getting full, taking a break");
                        Thread.Sleep(500);
                    }
                    else
                    {
                        try
                        {
                            lock (_repositionLocker)
                            {
                                if (deCompressor == null)
                                {
                                    // don't think these details matter too much - just help ACM select the right codec
                                    // however, the buffered provider doesn't know what sample rate it is working at
                                    // until we have a frame
                                    deCompressor          = CreateFrameDeCompressor();
                                    _bufferedWaveProvider = new BufferedWaveProvider(deCompressor.OutputFormat)
                                    {
                                        // allow us to get well ahead of ourselves
                                        BufferDuration          = TimeSpan.FromSeconds(MaxBufferSizeSeconds),
                                        DiscardOnBufferOverflow = true,
                                        ReadFully = true
                                    };
                                }
                                else
                                {
                                    var frame = Mp3Frame.LoadFromStream(_reader);
                                    if (frame != null)
                                    {
                                        int decompressed = deCompressor.DecompressFrame(frame, _decompressBuffer, 0);
                                        _bufferedWaveProvider.AddSamples(_decompressBuffer, 0, decompressed);
                                    }
                                    else // end of stream
                                    {
                                        _fullyDownloaded = true;
                                        if (_bufferedWaveProvider.BufferedBytes == 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        catch (EndOfStreamException)
                        {
                            _fullyDownloaded = true;
                            // reached the end of the MP3 file / stream
                            // break;
                        }
                    }
                } while (_playbackState != StreamingPlaybackState.Stopped);

                Debug.WriteLine("Exiting");
                // was doing this in a finally block, but for some reason
                // we are hanging on response stream .Dispose so never get there
                deCompressor?.Dispose();
            }
            catch (WebException e)
                when(e.Status == WebExceptionStatus.RequestCanceled)
                {
                    // ignored cancel exceptions
                    Stop();
                }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Stop();
            }
            finally
            {
                _fullyDownloaded = true;
                deCompressor?.Dispose();
            }
        }
        /// <summary>
        /// stream a mp3 audio
        /// </summary>
        public void StreamMp3()
        {
            fullyDownloaded = false;
            if (audioUrl != null && !string.IsNullOrEmpty(audioUrl))
            {
                try
                {
                    webRequest = (HttpWebRequest)WebRequest.Create(audioUrl);
                }
                catch (UriFormatException)
                {
                    Debug.WriteLine("URL format is not valid");
                    playbackState = StreamingPlaybackState.Stopped;
                    return;
                }
                catch (Exception)
                {
                    Debug.WriteLine("Error in web request create");
                    playbackState = StreamingPlaybackState.Stopped;
                    return;
                }
                HttpWebResponse resp;
                try
                {
                    resp = (HttpWebResponse)webRequest.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.RequestCanceled)
                    {
                        Debug.WriteLine("Web Exception error : " + e.Message);
                        playbackState = StreamingPlaybackState.Stopped;
                    }
                    return;
                }
                var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

                IMp3FrameDecompressor decompressor = null;

                try
                {
                    using (var responseStream = resp.GetResponseStream())
                    {
                        var readFullyStream = new ReadFullyStream(responseStream);
                        do
                        {
                            if (IsBufferNearlyFull)
                            {
                                Debug.WriteLine("Buffer getting full, taking a break");
                                Thread.Sleep(500);
                            }
                            else
                            {
                                // read next mp3 frame
                                Mp3Frame frame;
                                try
                                {
                                    frame = Mp3Frame.LoadFromStream(readFullyStream);
                                }
                                catch (EndOfStreamException)
                                {
                                    fullyDownloaded = true;
                                    // reached the end of the MP3 file / stream
                                    playbackState = StreamingPlaybackState.Stopped;
                                    break;
                                }
                                catch (WebException)
                                {
                                    break;
                                }

                                if (decompressor == null)
                                {
                                    // don't think these details matter too much - just help ACM select the right codec
                                    // however, the buffered provider doesn't know what sample rate it is working at
                                    // until we have a frame
                                    decompressor         = CreateFrameDecompressor(frame);
                                    bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                    bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                    //this.bufferedWaveProvider.BufferedDuration = 250;
                                }
                                if (frame != null)
                                {
                                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                    //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                                    bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                                }
                                else
                                {
                                    fullyDownloaded = true;
                                    break;
                                }
                            }
                        }while (playbackState != StreamingPlaybackState.Stopped);

                        Debug.WriteLine("Exiting");
                        // was doing this in a finally block, but for some reason
                        // we are hanging on response stream .Dispose so never get there
                        decompressor.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Generic Error: " + ex.Message);
                    playbackState = StreamingPlaybackState.Stopped;
                }
                finally
                {
                    if (decompressor != null)
                    {
                        decompressor.Dispose();
                        decompressor = null;
                    }
                }
            }
        }
Example #19
0
            private void StreamMP3_New(object state)
            {
                byte[] buffer = new byte[16384 * 4];

                var readFullyStream       = state as System.IO.Stream;
                BufferedWaveProvider  bwp = null;
                IMp3FrameDecompressor dec = null;

                //  var wh = new System.Threading.ManualResetEvent( false );
                //   wh.Reset();

                try {
                    using (IWavePlayer waveOut = new WaveOut()) {
                        // waveOut.PlaybackStopped += waveOut_PlaybackStopped;
                        // waveOut.PlaybackStopped += (a, b) => { wh.Set(); };
                        do
                        {
                            Mp3Frame frame = Mp3Frame.LoadFromStream(readFullyStream, true);
                            if (frame == null)
                            {
                                break;
                            }
                            if (bwp == null)
                            {
                                // первый раз, создаем выходной буфер
                                dec = createFrameDecompressor(frame);
                                bwp = new BufferedWaveProvider(dec.OutputFormat);
                                bwp.BufferDuration = TimeSpan.FromSeconds(3);

                                volumeProvider        = new VolumeSampleProvider(new Pcm16BitToSampleProvider(bwp));
                                volumeProvider.Volume = 0.0f;

                                waveOut.Init(volumeProvider);
                                waveOut.Play();
                                if (OnStartPlay != null)
                                {
                                    OnStartPlay(this);
                                }
                            }



                            int decompressed = dec.DecompressFrame(frame, buffer, 0);
                            bwp.AddSamples(buffer, 0, decompressed);

                            // Спим и ждем пока буффер просрется
                            if (bwp.BufferLength - bwp.BufferedBytes < bwp.WaveFormat.AverageBytesPerSecond / 4)
                            {
                                int x = 0;
                                while (playbackState != StreamingPlaybackState.Stopped && x < 5)
                                {
                                    x++;
                                    Thread.Sleep(50);
                                }
                            }
                        } while (playbackState != StreamingPlaybackState.Stopped);
                        //

                        waveOut_PlaybackStopped(null, null);

                        if (playbackState != StreamingPlaybackState.Stopped)
                        {
                            while (bwp.BufferedDuration.TotalSeconds > 0)
                            {
                                Thread.Sleep(50);
                            }
                        }

                        waveOut.Stop();
                        // wh.WaitOne();
                    }
                } catch (Exception exe) {
                    //Console.lo
                    if (OnError != null)
                    {
                        OnError(this);
                    }
                } finally {
                    if (dec != null)
                    {
                        dec.Dispose();
                    }

                    readFullyStream.Close();

                    playbackState = StreamingPlaybackState.Deleted;
                }
            }
Example #20
0
        private void WaveStreamProc()
        {
            string icyStreamName = string.Empty;

            while (_streamShouldPlay)
            {
                ResetFeedInactivityTimeout();
                SetFeedActive(true, false);
                System.Threading.Thread.Sleep(new System.Random().Next(100, 1500));
                try
                {
                    Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkCyan, "Initiating connection to {0}", _streamName);
                    playbackState = StreamingPlaybackState.Buffering;
                    FirePropertyChangedAction(false);
                    bufferedWaveProvider = null;
                    fullyDownloaded      = false;
                    webRequest           = (HttpWebRequest)WebRequest.Create(Common.UrlHelper.GetCorrectedStreamURL(_streamURL));
                    //webRequest.Timeout = webRequest.Timeout * 20;
                    /*test - start*/
                    webRequest.Headers.Clear();
                    webRequest.Headers.Add("Icy-MetaData", "1");
                    SetupWebRequestSettings(webRequest);
                    /*test - end*/
                    HttpWebResponse resp;
                    try
                    {
                        resp = SmartGetWebResponse(webRequest);// (HttpWebResponse)webRequest.GetResponse();
                        string newUrl = string.Empty;
                        if (!ValidateResponse(resp, out newUrl, out icyStreamName))
                        {
                            if (!string.IsNullOrWhiteSpace(newUrl))
                            {
                                webRequest = (HttpWebRequest)WebRequest.Create(newUrl);
                                //webRequest.Timeout = webRequest.Timeout * 20;
                                /*test - start*/
                                webRequest.Headers.Clear();
                                webRequest.Headers.Add("Icy-MetaData", "1");
                                SetupWebRequestSettings(webRequest);
                                /*test - end*/
                                resp = SmartGetWebResponse(webRequest);// (HttpWebResponse)webRequest.GetResponse();
                                PrintHttpWebResponseHeader(resp, "WaveStreamProc.Redirected", out icyStreamName);
                            }
                        }
                    }
                    catch (WebException e)
                    {
                        if (e.Status == WebExceptionStatus.ProtocolError)
                        {
                            Common.DebugHelper.WriteExceptionToLog("WaveStreamProcessor.WebRequest.GetResponse", e, false, _streamURL);

                            try
                            {
                                System.Net.HttpWebResponse httpRes = e.Response as System.Net.HttpWebResponse;
                                if (httpRes != null && httpRes.StatusCode == HttpStatusCode.NotFound)
                                {
                                    SetFeedActive(false, false);
                                }
                            }
                            catch { }
                        }
                        if (e.Status != WebExceptionStatus.RequestCanceled)
                        {
                            //ConsoleHelper.ColorWriteLine(ConsoleColor.Red, "WaveStreamProcessor Error: {0}", e.Message);
                            //Common.DebugHelper.WriteExceptionToLog("WaveStreamProcessor Error", e, false);
                            InternalStopStream();
                            ClearStreamTitle();

                            SmartSleep(30 * 1000, string.Format("WebRequest.GetResponse: {0}", e.Status));
                        }
                        continue;
                    }
                    var buffer = new byte[16348 * 4];
                    IMp3FrameDecompressor decompressor = null;
                    try
                    {
                        int  metaInt = -1;
                        bool bIsIcy  = IsIcecastStream(resp, out metaInt);
                        if (!bIsIcy)
                        {
                            metaInt = -1;
                        }
                        using (var responseStream = resp.GetResponseStream())
                        {
                            Stream readFullyStream = null;
                            if (!string.IsNullOrWhiteSpace(icyStreamName))
                            {
                                UpdateStreamTitle(icyStreamName, false);
                                FirePropertyChangedAction(true);
                            }
                            if (bIsIcy && metaInt > 0)
                            {
                                readFullyStream = new ReadFullyStream(new IcyStream(responseStream, metaInt, ProcessIcyMetadata));
                            }
                            else
                            {
                                readFullyStream = new ReadFullyStream(responseStream);
                            }
                            do
                            {
                                if (IsBufferNearlyFull)
                                {
                                    SmartSleep(500);
                                    //ConsoleHelper.ColorWriteLine(ConsoleColor.DarkCyan, "Buffer is getting full, taking a break, {0}sec...", bufferedWaveProvider.BufferedDuration.TotalSeconds);
                                    //ConsoleHelper.ColorWriteLine(ConsoleColor.DarkCyan, "  {0}", _streamURL);
                                }
                                else
                                {
                                    Mp3Frame frame;
                                    try
                                    {
                                        frame = Mp3Frame.LoadFromStream(readFullyStream);
                                    }
                                    catch (EndOfStreamException eose)
                                    {
                                        fullyDownloaded = true;
                                        SmartSleep(1500, "EndOfStreamException");
                                        if (playbackState != StreamingPlaybackState.Stopped)
                                        {
                                            Common.DebugHelper.WriteExceptionToLog("Mp3Frame.LoadFromStream", eose, false, _streamURL);
                                        }
                                        continue;
                                    }
                                    catch (WebException wex)
                                    {
                                        InternalStopStream();
                                        SmartSleep(3 * 60 * 1000, "WebException");
                                        if (playbackState != StreamingPlaybackState.Stopped)
                                        {
                                            Common.DebugHelper.WriteExceptionToLog("Mp3Frame.LoadFromStream", wex, false, _streamURL);
                                        }
                                        continue;
                                    }
                                    if (frame != null)
                                    {
                                        KickFeedInactivityTimeout();
                                        SetFeedActive(true, true);
                                        if (decompressor == null)
                                        {
                                            try
                                            {
                                                Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkGray, "Creating MP3 Decompressor for {0}...", _streamURL);
                                                decompressor         = CreateFrameDecompressor(frame);
                                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20);

                                                processorWaveProvider = new ProcessorWaveProvider(_streamName, bufferedWaveProvider, _sigDelegate, _propertyChangedAction, _recordingEnabled, _recordingType, _recordingKickTime, _noiseFloor, _customNoiseFloor, _removeNoise, _decodeMDC1200, _decodeGEStar, _decodeFleetSync, _decodeP25);

                                                //volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);
                                                volumeProvider        = new VolumeWaveProvider16(processorWaveProvider);
                                                volumeProvider.Volume = _initialVolume;
                                                waveOut = CreateWaveOut();
                                                waveOut.Init(volumeProvider);
                                                FirePropertyChangedAction(false);
                                            }
                                            catch (Exception ex)
                                            {
                                                Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Red, "Excpetion in stream {0}: {1}", _streamURL, ex.Message);
                                                Common.DebugHelper.WriteExceptionToLog("WaveStreamProcessor", ex, false, string.Format("Exception in stream {0}", _streamURL));
                                                InternalStopStream();
                                                SmartSleep(3 * 60 * 1000, "Exception:CreateFrameDecompressor");
                                                continue;
                                            }
                                        }
                                        int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                        bufferedWaveProvider.AddSamples(buffer, 0, decompressed);

                                        var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds;
                                        if (bufferedSeconds < 0.5 && playbackState == StreamingPlaybackState.Playing && !fullyDownloaded)
                                        {
                                            playbackState = StreamingPlaybackState.Buffering;
                                            FirePropertyChangedAction(false);
                                            waveOut.Pause();
                                            Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkRed, "Stream Paused... Buffering... {0}", _streamURL);
                                        }
                                        else if (bufferedSeconds > 4 && playbackState == StreamingPlaybackState.Buffering)
                                        {
                                            waveOut.Play();
                                            playbackState = StreamingPlaybackState.Playing;
                                            FirePropertyChangedAction(false);
                                            Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkGreen, "Stream Playing... {0}", _streamURL);
                                        }
                                    }
                                    else
                                    {
                                        if (IsFeedInactive())
                                        {
                                            try
                                            {
                                                Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkYellow, "Restarting {0} due to inactivity...", _streamName);
                                                InternalStopStream();
                                            }
                                            finally
                                            {
                                                LongSmartSleep(FEED_NOT_ACTIVE_SLEEP_SECS, "WaveStreamProc.IsFeedInactive");
                                            }
                                        }
                                    }
                                }
                            }while (playbackState != StreamingPlaybackState.Stopped);
                            if (decompressor != null)
                            {
                                try
                                {
                                    decompressor.Dispose();
                                }
                                finally
                                {
                                    decompressor = null;
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (decompressor != null)
                        {
                            try
                            {
                                decompressor.Dispose();
                            }
                            finally
                            {
                                decompressor = null;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    Common.DebugHelper.WriteExceptionToLog("WaveStreamProc", ex, false, "General Catch");
#endif
                    try
                    {
                        InternalStopStream();
                    }
                    finally
                    {
                        LongSmartSleep(15, "WaveStreamProc");
                    }
                }
            }
        }
Example #21
0
        private async Task Play(Stream stream)
        {
            IMp3FrameDecompressor decompressor = null;
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            try
            {
                using var responseStream = stream;

                var readFullyStream = new ReadFullyStream(responseStream);
                do
                {
                    if (IsBufferNearlyFull)
                    {
                        Debug.WriteLine("Buffer getting full, taking a break");
                        await Task.Delay(500);
                    }
                    else
                    {
                        Mp3Frame frame;
                        try
                        {
                            frame = Mp3Frame.LoadFromStream(readFullyStream);
                        }
                        catch (EndOfStreamException)
                        {
                            fullyDownloaded = true;
                            // reached the end of the MP3 file / stream
                            break;
                        }

                        if (frame == null)
                        {
                            break;
                        }

                        if (decompressor == null)
                        {
                            // don't think these details matter too much - just help ACM select the right codec
                            // however, the buffered provider doesn't know what sample rate it is working at
                            // until we have a frame
                            decompressor         = CreateFrameDecompressor(frame);
                            bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat)
                            {
                                BufferDuration = TimeSpan.FromSeconds(20) // allow us to get well ahead of ourselves
                            };
                            //this.bufferedWaveProvider.BufferedDuration = 250;
                        }

                        var decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                        Debug.WriteLine(string.Format("Decompressed a frame {0}", decompressed));
                        bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                    }
                } while (playbackState != StreamingPlaybackState.Stopped);

                Debug.WriteLine("Exiting");
                // was doing this in a finally block, but for some reason
                // we are hanging on response stream .Dispose so never get there
                decompressor.Dispose();
            }
            finally
            {
                decompressor?.Dispose();
            }
        }
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            string path = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(path);
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    Console.WriteLine(e.Message);
                }
                return;
            }

            var buffer = new byte[16384 * 4];

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Console.WriteLine("buffer getting full, sleeping.");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                                if (frame == null)
                                {
                                    throw new EndOfStreamException();
                                }
                            }
                            catch (EndOfStreamException)
                            {
                                Console.WriteLine("Stream Fully Downloaded");
                                fullyDownloaded = true;
                                break;
                            }
                            catch (WebException)
                            {
                                Console.WriteLine("Stream Download Stopped");
                                break;
                            }
                            if (decompressor == null)
                            {
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20);
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Example #23
0
        /// <summary>
        /// Reads decompressed PCM data from our MP3 file.
        /// </summary>
        public override int Read(byte[] sampleBuffer, int offset, int numBytes)
        {
            int bytesRead = 0;

            lock (repositionLock)
            {
                if (decompressLeftovers != 0)
                {
                    int toCopy = Math.Min(decompressLeftovers, numBytes);
                    Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
                    decompressLeftovers -= toCopy;
                    if (decompressLeftovers == 0)
                    {
                        decompressBufferOffset = 0;
                    }
                    else
                    {
                        decompressBufferOffset += toCopy;
                    }
                    bytesRead += toCopy;
                    offset    += toCopy;
                }

                int targetTocIndex = tocIndex; // the frame index that contains the requested data

                if (repositionedFlag)
                {
                    decompressor.Reset();

                    // Seek back a few frames of the stream to get the reset decoder decode a few
                    // warm-up frames before reading the requested data. Without the warm-up phase,
                    // the first half of the frame after the reset is attenuated and does not resemble
                    // the data as it would be when reading sequentially from the beginning, because
                    // the decoder is missing the required overlap from the previous frame.
                    tocIndex           = Math.Max(0, tocIndex - 3); // no warm-up at the beginning of the stream
                    mp3Stream.Position = tableOfContents[tocIndex].FilePosition;

                    repositionedFlag = false;
                }

                while (bytesRead < numBytes)
                {
                    Mp3Frame frame = ReadNextFrame();
                    if (frame != null)
                    {
                        int decompressed = decompressor.DecompressFrame(frame, decompressBuffer, 0);

                        if (tocIndex <= targetTocIndex || decompressed == 0)
                        {
                            // The first frame after a reset usually does not immediately yield decoded samples.
                            // Because the next instructions will fail if a buffer offset is set and the frame
                            // decoding didn't return data, we skip the part.
                            // We skip the following instructions also after decoding a warm-up frame.
                            continue;
                        }
                        // Two special cases can happen here:
                        // 1. We are interested in the first frame of the stream, but need to read the second frame too
                        //    for the decoder to return decoded data
                        // 2. We are interested in the second frame of the stream, but because reading the first frame
                        //    as warm-up didn't yield any data (because the decoder needs two frames to return data), we
                        //    get data from the first and second frame.
                        //    This case needs special handling, and we have to purge the data of the first frame.
                        else if (tocIndex == targetTocIndex + 1 && decompressed == bytesPerDecodedFrame * 2)
                        {
                            // Purge the first frame's data
                            Array.Copy(decompressBuffer, bytesPerDecodedFrame, decompressBuffer, 0, bytesPerDecodedFrame);
                            decompressed = bytesPerDecodedFrame;
                        }

                        int toCopy = Math.Min(decompressed - decompressBufferOffset, numBytes - bytesRead);
                        Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
                        if ((toCopy + decompressBufferOffset) < decompressed)
                        {
                            decompressBufferOffset = toCopy + decompressBufferOffset;
                            decompressLeftovers    = decompressed - decompressBufferOffset;
                        }
                        else
                        {
                            // no lefovers
                            decompressBufferOffset = 0;
                            decompressLeftovers    = 0;
                        }
                        offset    += toCopy;
                        bytesRead += toCopy;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Debug.Assert(bytesRead <= numBytes, "MP3 File Reader read too much");
            position += bytesRead;
            return(bytesRead);
        }
Example #24
0
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            var url = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(url);

            // To retrieve ShoutCAST metadata
            int metaInt = 0; // blocksize of mp3 data

            webRequest.Headers.Clear();
            webRequest.Headers.Add("GET", "/ HTTP/1.0");
            // needed to receive metadata informations
            webRequest.Headers.Add("Icy-MetaData", "1");
            webRequest.UserAgent = "WinampMPEG/5.09";

            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    throw;
                    //ShowError(e.Message);
                }
                return;
            }
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            try
            {
                // read blocksize to find metadata block
                metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
            }
            catch
            {
            }


            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ShoutcastStream(responseStream);
                    readFullyStream.MetaInt = metaInt;

                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);

                                if (metaInt > 0)
                                {
                                    StreamTitle = (readFullyStream.StreamTitle);
                                }
                                else
                                {
                                    StreamTitle = STR_TITLE_NOT_AVAIL;
                                }
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException)
                            {
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                //this.bufferedWaveProvider.BufferedDuration = 250;

                                // Set the bitrate property
                                this.StreamBitrate = frame.BitRate;
                            }
                            try
                            {
                                int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                            }
                            catch
                            {
                                if (this.State == StreamingPlaybackState.Stopped)
                                {
                                    return;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Example #25
0
        public static void receivingSong()
        {
            waveOut = new WaveOut();
            decomp  = null;


            int count  = 0;
            var buffer = new byte[16384 * 4];

            do
            {
                current = Thread.CurrentThread;
                if (bufferedWaveProvider != null && bufferedWaveProvider.BufferedDuration.TotalSeconds > 5)
                {
                    Thread.Sleep(200);
                    if (buffering == false)
                    {
                        break;
                    }
                }
                byte[] receivedData = new byte[2000];
                if (!receiveData(ref receivedData))
                {
                    break;
                }

                if (Encoding.ASCII.GetString(receivedData) == "done")
                {
                    break;
                }
                else
                {
                    client.Send(Encoding.ASCII.GetBytes("more"), 4);    // Nhan change value here
                }
                Mp3Frame frame;
                Stream   ms = new MemoryStream();

                ms.Write(receivedData, 0, receivedData.Length);
                ms.Position = 0;

                frame = Mp3Frame.LoadFromStream(ms, true);
                if (decomp == null)
                {
                    try
                    {
                        WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                  frame.FrameLength, frame.BitRate);
                        decomp = new AcmMp3FrameDecompressor(waveFormat);
                    }
                    catch
                    {
                        break;
                    }
                    bufferedWaveProvider = new BufferedWaveProvider(decomp.OutputFormat);
                    bufferedWaveProvider.BufferDuration =
                        TimeSpan.FromSeconds(20);
                }
                if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 5 && waveOut.PlaybackState == PlaybackState.Stopped && buffering == true)
                {
                    try
                    {
                        waveOut.Init(bufferedWaveProvider);
                        waveOut.Play();
                    }
                    catch
                    {
                        break;
                    }
                }
                try
                {
                    int decompressed = decomp.DecompressFrame(frame, buffer, 0);
                    bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                }
                catch
                {
                    break;
                }


                count++;
            } while (buffering);
        }
Example #26
0
        private void StreamMp3(object nothing)
        {
            if (frameInputStream == null)
            {
                frameInputStream = new MemoryStream(1024 * 1024); //1MB
            }
            readFullyStream = new ReadFullyStream(frameInputStream);
            Mp3Frame frame;

            byte[] buff = new byte[16384 * 4];

            while (!disposed)
            {
                if (playState == PlayState.playing && !decompressDone)
                {
                    try
                    {
                        if (frameIndex >= frameList.Length)
                        {
                            decompressDone = true;
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        continue;
                    }

                    if (IsBufferNearlyFull)
                    {
                        Thread.Sleep(500);
                    }
                    else
                    {
                        lock (setMediaLock)
                        {
                            try
                            {
                                if (Monitor.TryEnter(frameIndexLock, 500))
                                {
                                    if (frameList == null)
                                    {
                                        continue;
                                    }

                                    if (frameList[frameIndex] == null)
                                    {
                                        if ((DateTime.Now - lastGotFrameTime).TotalMilliseconds > 3000)
                                        {
                                            Console.WriteLine("@@@@@@@@@@ Recourse Data @@@@@@@@@@");
                                            checkChunk(frameIndex, out frameCheckPoint);
                                        }
                                        Thread.Sleep(100);
                                        continue;
                                    }
                                    frameInputStream.Position = 0;
                                    frameInputStream.Write(frameList[frameIndex], 0, frameList[frameIndex].Length);
                                    frameInputStream.Position = 0;
                                    frameIndex++;
                                }
                            }
                            finally
                            {
                                Monitor.PulseAll(frameIndexLock);
                                Monitor.Exit(frameIndexLock);
                            }


                            try
                            {
                                frame = Mp3Frame.LoadFromStream(frameInputStream);
                                if (frame == null)
                                {
                                    continue;
                                }
                            }
                            catch (Exception)
                            {
                                continue;
                            }

                            if (decompressor == null)
                            {
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                          frame.FrameLength, frame.BitRate);
                                decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20);
                                volumeProvider        = new VolumeWaveProvider16(bufferedWaveProvider);
                                volumeProvider.Volume = mVolume;
                                waveOut.Init(volumeProvider);
                                waveoutInited = true;
                            }

                            try
                            {
                                int decompressed = decompressor.DecompressFrame(frame, buff, 0);
                                bufferedWaveProvider.AddSamples(buff, 0, decompressed);
                            }
                            catch (NAudio.MmException e)
                            {
                                Console.WriteLine(e);
                            }

                            Monitor.PulseAll(setMediaLock);
                        }
                    }
                }
                else
                {
                    if (playState == PlayState.playing && playDuration >= totalMilliseconds / 1000)
                    {
                        playState = PlayState.mediaEnded;
                        stop();
                    }
                    Thread.Sleep(50);
                }
            }
        }
Example #27
0
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            var url = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Clear();
            webRequest.Headers.Add("Icy-MetaData", "1");
            HttpWebResponse resp;
            var             metaInt = 0;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
                if (resp.Headers.AllKeys.Contains("icy-metaint"))
                {
                    metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
                }
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    _log.Error(e.Message);
                }
                return;
            }
            var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    readFullyStream = new ReadFullyStream(responseStream, metaInt);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            _log.Verbose("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException)
                            {
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (frame == null)
                            {
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration =
                                    TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                //this.bufferedWaveProvider.BufferedDuration = 250;
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    _log.Verbose("Exiting");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
        private void Stream2Mp3(object state)
        {
            try
            {
                fullyDownloaded2 = false;
                var url = (string)state;
                requisicaodaweb2           = (HttpWebRequest)WebRequest.Create(url);
                requisicaodaweb2.UserAgent = "GabardoHost GET URL";
                HttpWebResponse resp;
                try
                {
                    resp = (HttpWebResponse)requisicaodaweb2.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.RequestCanceled)
                    {
                        ShowError(e.Message + e.StackTrace);
                    }
                    return;
                }
                var buffer2 = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

                IMp3FrameDecompressor decompressor2 = null;
                try
                {
                    using (var responseStream = resp.GetResponseStream())
                    {
                        var readFullyStream = new ReadFullyStream(responseStream);
                        do
                        {
                            if (IsBufferNearlyFull2)
                            {
                                //Debug.WriteLine("Buffer getting full, taking a break");
                                System.Threading.Thread.Sleep(500);
                            }
                            else
                            {
                                Mp3Frame frame;
                                try
                                {
                                    frame = Mp3Frame.LoadFromStream(readFullyStream);
                                }
                                catch (EndOfStreamException)
                                {
                                    fullyDownloaded2 = true;
                                    // reached the end of the MP3 file / stream
                                    break;
                                }
                                catch (WebException)
                                {
                                    // probably we have aborted download from the GUI thread
                                    break;
                                }
                                if (frame == null)
                                {
                                    break;
                                }
                                if (decompressor2 == null)
                                {
                                    // don't think these details matter too much - just help ACM select the right codec
                                    // however, the buffered provider doesn't know what sample rate it is working at
                                    // until we have a frame
                                    decompressor2     = CreateFrameDecompressor(frame);
                                    provedordebuffer2 = new BufferedWaveProvider(decompressor2.OutputFormat);
                                    provedordebuffer2.BufferDuration = TimeSpan.FromSeconds(int.Parse(txtBuffer2.Text));
                                    // allow us to get well ahead of ourselves this.bufferedWaveProvider.BufferedDuration = 250;
                                }
                                int decompressed2 = decompressor2.DecompressFrame(frame, buffer2, 0);
                                //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                                provedordebuffer2.AddSamples(buffer2, 0, decompressed2);
                            }
                        }while (estadodoplay2 != StreamingPlaybackState.Stopped);
                        // Debug.WriteLine("Exiting");
                        // was doing this in a finally block, but for some reason
                        // we are hanging on response stream .Dispose so never get there
                        decompressor2.Dispose();
                    }
                }
                finally
                {
                    if (decompressor2 != null)
                    {
                        decompressor2.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(ex.Message + ex.StackTrace);
            }
        }
Example #29
0
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            string url = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(url);
            int metaInt = 0;             // blocksize of mp3 data

            webRequest.Headers.Clear();
            webRequest.Headers.Add("GET", "/ HTTP/1.0");
            webRequest.Headers.Add("Icy-MetaData", "1");
            webRequest.UserAgent = "WinampMPEG/5.09";
            HttpWebResponse resp;

            try {
                resp = (HttpWebResponse)webRequest.GetResponse();
            } catch (WebException e) {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    System.Console.WriteLine(e.Message);
                }
                return;
            }
            byte[] buffer =
                new byte[16384 * 4];                         // needs to be big enough to hold a decompressed frame
            try {
                // read blocksize to find metadata block
                metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
            } catch {}
            IMp3FrameDecompressor decompressor = null;

            try {
                using (Stream responseStream = resp.GetResponseStream()) {
                    ReadFullyStream readFullyStream = new ReadFullyStream(responseStream);
                    readFullyStream.MetaInt = metaInt;
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            System.Console.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(1000);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                                if (metaInt > 0 && !subbedToEvent)
                                {
                                    subbedToEvent = true;
                                    readFullyStream.StreamTitleChanged +=
                                        ReadFullyStream_StreamTitleChanged;
                                }
                                else if (metaInt <= 0)
                                {
                                    song_info = "none";
                                }
                            } catch (EndOfStreamException) {
                                fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            } catch (WebException) {
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (frame == null)
                            {
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select
                                // the right codec however, the buffered provider doesn't know what
                                // sample rate it is working at until we have a frame
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider =
                                    new BufferedWaveProvider(decompressor.OutputFormat)
                                {
                                    BufferDuration = TimeSpan.FromSeconds(
                                        30)                                                                 // allow us to get well ahead of ourselves
                                };
                                // this.bufferedWaveProvider.BufferedDuration = 250;

                                decomp = true;                                 // hack to tell main Unity Thread to create AudioClip
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    System.Console.WriteLine("Exiting Thread");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor.Dispose();
                    readFullyStream.Close();
                }
            } finally {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
        private void Result_Button_Clicked(object sender, EventArgs e, String id, String title)
        {
            fullyDownloaded = false;
            webRequest      = (HttpWebRequest)WebRequest.Create("http://lowdatayt.ddns.net:8000/api/search/" + id + ", '" + title + "'");
            //test with definitively working mp3 stream
            //webRequest = (HttpWebRequest)WebRequest.Create("http://listen.openstream.co/3162/audio");
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException x)
            {
                if (x.Status != WebExceptionStatus.RequestCanceled)
                {
                    Console.WriteLine(x);
                }
                return;
            }
            var buffer = new byte[16384 * 4];
            IMp3FrameDecompressor decompressor = null;

            try{
                using (var responsestream = resp.GetResponseStream())
                {
                    var readFullyStream = new Services.ReadFullyStream(responsestream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Console.WriteLine("buffer getting full");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;
                                break;
                            }
                            catch (WebException)
                            {
                                break;
                            }
                            if (frame == null)
                            {
                                break;
                            }
                            if (decompressor == null)
                            {
                                decompressor         = CreateFrameDecompressor(frame);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20);
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    Console.WriteLine("exiting");
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }