Esempio n. 1
0
        /// <summary>
        /// Disposes this WaveStream
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                while (this.TableCreater.IsAlive)
                {
                    this.tableCreated = true;
                    Thread.Sleep(1);
                }

                if (Mp3Stream != null)
                {
                    if (ownInputStream)
                    {
                        Mp3Stream.Dispose();
                    }
                    Mp3Stream = null;
                }
                if (decompressor != null)
                {
                    decompressor.Dispose();
                    decompressor = null;
                }
            }
            base.Dispose(disposing);
        }
Esempio n. 2
0
        protected override void RipLoopCleanup()
        {
            if (_decompressor != null)
            {
                _decompressor.Dispose();
                _decompressor = null;
            }

            _waveFormat   = null;
            _currentFrame = null;
        }
Esempio n. 3
0
        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();
                }
            }
        }
Esempio n. 4
0
        private void CleanUpAudio()
        {
            if (waveOut != null)
            {
                waveOut.Stop();
                waveOut.Dispose();
                waveOut = null;
            }

            if (decompressor != null)
            {
                decompressor.Dispose();
                decompressor = null;
            }

            bufferedWaveProvider = null;
            stream.Flush();
        }
Esempio n. 5
0
 /// <summary>
 /// Disposes this WaveStream
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (mp3Stream != null)
         {
             if (ownInputStream)
             {
                 mp3Stream.Dispose();
             }
             mp3Stream = null;
         }
         if (decompressor != null)
         {
             decompressor.Dispose();
             decompressor = null;
         }
     }
     base.Dispose(disposing);
 }
Esempio n. 6
0
        public override void Dispose()
        {
            if (_task.Status == TaskStatus.Running)
            {
                _tokenSource.Cancel();
                _task.Wait(TimeSpan.FromSeconds(1));
                if (_task.Status < TaskStatus.RanToCompletion)
                {
                    Trace.TraceWarning($"Aborted task of '{nameof(Mp3StreamChannel)}'.");
                }
                else
                {
                    _task.Dispose();
                }
            }
            _tokenSource.Dispose();


            _decompressor?.Dispose();
            _stream.Dispose();

            base.Dispose();
        }
Esempio n. 7
0
        /// <summary>Liek MP3 plūsmu buferī.</summary>
        private async Task StreamMp3()
        {
            try { await stream.Open(); } catch { unexpectedStop.BeginInvoke(null, null); return; }
            IMp3FrameDecompressor decompressor = null;

            byte[] buffer       = new byte[65536];     // Atspiests skaņas fragments.
            bool   hasException = false;

            PlaybackState = PlaybackState.Buffering;
            playbackTimer.Start();
            int sampleRate = 0;           // Iepriekšēja skaņas fragmenta frekvence, piemēram, 44100.

            while (PlaybackState == PlaybackState.Buffering || PlaybackState == PlaybackState.Playing)
            {
                if (bufferedWaveProvider != null &&
                    bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                {
                    await Task.Delay(500);                     // Kamēr buferī pietiekami datu, lejuplāde var pagaidīt.

                    continue;
                }
                Mp3Frame frame = null;
                try { frame = Mp3Frame.LoadFromStream(stream); } catch (Exception) {
                    hasException = PlaybackState != PlaybackState.Stopped;
                    break;
                }
                if (frame.SampleRate != sampleRate)
                {
                    if (decompressor == null)
                    {
                        waveOut = new WaveOut();
                    }
                    else
                    {
                        decompressor.Dispose();
                    }
                    Debug.WriteLine("{0} Hz, {1} bps, {2} bytes", frame.SampleRate, frame.BitRate, frame.FrameLength);
                    // Sagatavo dekoderi saskaņā ar pirmā skaņas fragmenta īpatnībām.
                    decompressor = new AcmMp3FrameDecompressor(
                        new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate));
                    bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                    bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(3);
                    volumeProvider        = new VolumeWaveProvider16(bufferedWaveProvider);
                    volumeProvider.Volume = isMuted?0:volume;
                    if (waveOut == null)
                    {
                        break;                                      // Kad apstādina atskaņošanu, tad novērš kļūdu nākamā rindā.
                    }
                    waveOut.Init(volumeProvider);
                    // Frekvencei jābūt nemainīgai visas plūsmas garumā, bet var tikt nepareizi noteikta pēc pirmā fragmenta.
                    sampleRate = frame.SampleRate;
                }
                try {
                    bufferedWaveProvider.AddSamples(buffer, 0, decompressor.DecompressFrame(frame, buffer, 0));
                } catch { hasException = true; break; }
            }
            ;
            if (PlaybackState != PlaybackState.Stopped)
            {
                stream.Close();
            }
            if (decompressor != null)
            {
                decompressor.Dispose();
            }
            if (hasException)
            {
                unexpectedStop.BeginInvoke(null, null);
            }
        }
Esempio n. 8
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();
            }
        }
Esempio n. 9
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();
            }
        }
Esempio n. 10
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();
                }
            }
        }
Esempio n. 11
0
        private void StreamMp3(CancellationToken cancelToken)
        {
            //16384*4
            var buffer = new byte[16384]; // needs to be big enough to hold a decompressed frame

            if (String.IsNullOrEmpty(file))
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(url);

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

                IMp3FrameDecompressor decompressor = null;
                try
                {
                    using (var responseStream = resp.GetResponseStream())
                    {
                        PlayStream(responseStream, cancelToken, buffer, decompressor);

                        Console.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();
                        }
                    }
                }

                finally
                {
                    if (decompressor != null)
                    {
                        decompressor.Dispose();
                    }
                }
            }
            else
            {
                using (var responseStream = File.OpenRead(file))
                {
                    PlayStream(responseStream, cancelToken, buffer);

                    Console.WriteLine("Exiting");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                }
            }
        }
Esempio n. 12
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();
        }
Esempio n. 13
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");
                    }
                }
            }
        }
Esempio n. 14
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();
                }
            }
        }
Esempio n. 15
0
        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();
                }
            }
        }
Esempio n. 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();
                }
            }
        }
Esempio n. 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;
                    }
                }
            }
        }
Esempio n. 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;
                }
            }
Esempio n. 20
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();
            }
        }
Esempio n. 21
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);
            }
        }
Esempio n. 23
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();
                }
            }
        }