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);
        }
Exemple #2
0
 private static BufferedWaveProvider CreateBufferedWaveProvider(IMp3FrameDecompressor decompressor)
 {
     return(new BufferedWaveProvider(decompressor.OutputFormat)
     {
         BufferDuration = TimeSpan.FromSeconds(1)
     });
 }
Exemple #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);
        }
Exemple #4
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);
        }
Exemple #5
0
        public static void playMusic(UdpClient privatePort, IPEndPoint privateEP)
        {
            string mediaFolder = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "MusicLibrary");

            byte[] data;
            int    count1        = 0;
            var    buffer1       = new byte[16384 * 4];
            var    nameOfTheSong = privatePort.Receive(ref privateEP);
            var    startPoint    = privatePort.Receive(ref privateEP);
            Song   sendingSong   = null;

            try
            {
                sendingSong = allSongs.Songs.Where(x => x.ToString() == Encoding.ASCII.GetString(nameOfTheSong)).Single();
            }
            catch
            {
                var msg = Encoding.ASCII.GetBytes("Error occurred: Couldn't find this song in our library");
                privatePort.Send(msg, msg.Length, privateEP);
            }
            privatePort.Send(Encoding.ASCII.GetBytes("granted"), 7, privateEP);
            if (sendingSong != null)
            {
                int           startTime = Int32.Parse(Encoding.ASCII.GetString(startPoint));
                Mp3FileReader reader    = new Mp3FileReader(mediaFolder + "\\" + sendingSong.Directory);
                var           b         = Encoding.ASCII.GetBytes(reader.TotalTime.ToString());
                privatePort.Send(b, b.Length, privateEP);
                reader.CurrentTime = TimeSpan.FromSeconds(startTime);
                Mp3Frame mp3Frame = reader.ReadNextFrame();

                IMp3FrameDecompressor decomp     = null;
                WaveFormat            waveFormat = new Mp3WaveFormat(mp3Frame.SampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                     mp3Frame.FrameLength, mp3Frame.BitRate);
                decomp = new AcmMp3FrameDecompressor(waveFormat);
                int total = 0;
                while (mp3Frame != null)
                {
                    data = mp3Frame.RawData;
                    privatePort.Send(data, data.Length, privateEP);
                    if (Encoding.ASCII.GetString(privatePort.Receive(ref privateEP)) != "more")
                    {
                        break;
                    }

                    total += data.Length;
                    if (count1 % 500 == 0)
                    {
                        Console.WriteLine(" Sending Song: " + sendingSong.ToString());
                        Console.WriteLine("Total packet sent: " + total);
                    }

                    count1   = count1 + 1;
                    mp3Frame = reader.ReadNextFrame();
                }
                privatePort.Send(Encoding.ASCII.GetBytes("done"), 4, privateEP);
                Console.WriteLine("Total packet sent: " + total);
                Console.WriteLine("------Stop Sending------");
            }
        }
Exemple #6
0
        /// <summary>
        /// Opens MP3 from a stream rather than a file
        /// Will not dispose of this stream itself
        /// </summary>
        /// <param name="inputStream">The incoming stream containing MP3 data</param>
        /// <param name="frameDecompressorBuilder">Factory method to build a frame decompressor</param>
        public Mp3FileReader(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder)
        {
            // Calculated as a double to minimize rounding errors

            mp3Stream = inputStream;
            id3v2Tag  = Id3v2Tag.ReadTag(mp3Stream);

            dataStartPosition = mp3Stream.Position;
            var mp3Frame = Mp3Frame.LoadFromStream(mp3Stream);

            sampleRate         = mp3Frame.SampleRate;
            frameLengthInBytes = mp3Frame.FrameLength;
            double bitRate = mp3Frame.BitRate;

            xingHeader = XingHeader.LoadXingHeader(mp3Frame);
            // If the header exists, we can skip over it when decoding the rest of the file
            if (xingHeader != null)
            {
                dataStartPosition = mp3Stream.Position;
            }

            mp3DataLength = mp3Stream.Length - dataStartPosition;

            // try for an ID3v1 tag as well
            mp3Stream.Position = mp3Stream.Length - 128;
            byte[] tag = new byte[128];
            mp3Stream.Read(tag, 0, 3);
            if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
            {
                id3v1Tag       = tag;
                mp3DataLength -= 128;
            }

            mp3Stream.Position = dataStartPosition;

            // create a temporary MP3 format before we know the real bitrate
            Mp3WaveFormat = new Mp3WaveFormat(sampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frameLengthInBytes, (int)bitRate);

            CreateTableOfContents();
            tocIndex = 0;

            // [Bit rate in Kilobits/sec] = [Length in kbits] / [time in seconds]
            //                            = [Length in bits ] / [time in milliseconds]

            // Note: in audio, 1 kilobit = 1000 bits.
            bitRate = (mp3DataLength * 8.0 / TotalSeconds());

            mp3Stream.Position = dataStartPosition;

            // now we know the real bitrate we can create an accurate
            Mp3WaveFormat  = new Mp3WaveFormat(sampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frameLengthInBytes, (int)bitRate);
            decompressor   = frameDecompressorBuilder(Mp3WaveFormat);
            waveFormat     = decompressor.OutputFormat;
            bytesPerSample = (decompressor.OutputFormat.BitsPerSample) / 8 * decompressor.OutputFormat.Channels;
            // no MP3 frames have more than 1152 samples in them
            // some MP3s I seem to get double
            decompressBuffer = new byte[1152 * bytesPerSample * 2];
        }
Exemple #7
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);
            }
        }
        protected override void RipLoopCleanup()
        {
            if (_decompressor != null)
            {
                _decompressor.Dispose();
                _decompressor = null;
            }

            _waveFormat   = null;
            _currentFrame = null;
        }
        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();
                }
            }
        }
Exemple #10
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));
        }
Exemple #11
0
        private void CleanUpAudio()
        {
            if (waveOut != null)
            {
                waveOut.Stop();
                waveOut.Dispose();
                waveOut = null;
            }

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

            bufferedWaveProvider = null;
            stream.Flush();
        }
Exemple #12
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);
 }
Exemple #13
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (this.mp3Stream != null)
         {
             if (this.ownInputStream)
             {
                 this.mp3Stream.Dispose();
             }
             this.mp3Stream = null;
         }
         if (this.decompressor != null)
         {
             this.decompressor.Dispose();
             this.decompressor = null;
         }
     }
     base.Dispose(disposing);
 }
Exemple #14
0
        public void requestMp3(string fileName)
        {
            if (Monitor.TryEnter(setMediaLock, 3000))
            {
                latestRequest.mp3Name = fileName;
                latestRequest.done    = false;

                if (playState == PlayState.playing)
                {
                    stop();
                }

                if (waveoutInited)
                {
                    bufferedWaveProvider = null;
                    volumeProvider       = null;
                    decompressor         = null;
                    waveoutInited        = false;
                    decompressDone       = false;

                    if (waveOut != null)
                    {
                        waveOut.Dispose();
                        waveOut = new WaveOutEvent();
                    }
                }

                lock (frameListLock)
                {
                    frameList = null;
                    Monitor.PulseAll(frameListLock);
                }
                mm.SendMessage(new Message(MessageCode.requestMp3, fileName));
                latestRequest.requestTime = DateTime.Now;
                currentMp3  = fileName;
                playStartAt = -1;
                Monitor.PulseAll(setMediaLock);
                Monitor.Exit(setMediaLock);
            }
        }
Exemple #15
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
        }
Exemple #16
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 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();
                }
            }
        }
Exemple #18
0
        private void StreamMp3(object state)
        {
            _isBuffering(true);

            ThrottledStream responseStream = (ThrottledStream)state;

            byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (responseStream)
                {
                    _playbackState = StreamingPlaybackState.Buffering;

                    using (var readFullyStream = new ReadFullyStream(responseStream))
                    {
                        do
                        {
                            if (_bufferedWaveProvider != null &&
                                _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes <
                                _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                            {
                                Thread.Sleep(500);
                            }

                            Mp3Frame frame;

                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);

                                if (frame == null)
                                {
                                    _fullyDownloaded = true;
                                    break;
                                }
                            }
                            catch (EndOfStreamException e)
                            {
                                _log.Log(e.Message, Category.Warn, Priority.Medium);
                                _fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException e)
                            {
                                _log.Log(e.Message, Category.Warn, Priority.Medium);
                                _fullyDownloaded = true;
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            catch (Exception e)
                            {
                                _log.Log(e.Message, Category.Exception, Priority.High);
                                _fullyDownloaded = true;
                                break;
                            }

                            if (decompressor == null)
                            {
                                WaveFormat waveFormat = new Mp3WaveFormat(44100,
                                                                          frame.ChannelMode == ChannelMode.Mono
                                                                              ? 1
                                                                              : 2, frame.FrameLength, frame.BitRate);
                                decompressor          = new AcmMp3FrameDecompressor(waveFormat);
                                _bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);

                                if (_track.TotalDuration != TimeSpan.Zero)
                                {
                                    _bufferedWaveProvider.BufferDuration = _track.TotalDuration;
                                }
                                else
                                {
                                    _bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(25);
                                }

                                responseStream.MaximumBytesPerSecond = _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4;
                            }

                            if (_bufferedWaveProvider != null)
                            {
                                try
                                {
                                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                    _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                                }
                                catch (Exception e)
                                {
                                    _fullyDownloaded = true;
                                    _log.Log("Grooveshark: Error decompressing frame: " + e.Message, Category.Exception, Priority.Medium);
                                    break;
                                }
                            }
                        } 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
                        if (decompressor != null)
                        {
                            decompressor.Dispose();
                            decompressor = null;
                        }
                    }
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                    decompressor = null;
                }
            }

            _log.Log("Grooveshark: Buffer thread exiting", Category.Info, Priority.Medium);
        }
Exemple #19
0
        private void StreamMP3()
        {
            _abort = new ManualResetEvent(false);
            HttpWebRequest request = null;

            try
            {
                var resp   = _connFactory.GetResponse(_source, "GET", "", out request);
                var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
                IMp3FrameDecompressor decompressor = null;

                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    while (!_abort.WaitOne(20) && !MainForm.ShuttingDown)
                    {
                        if (_bufferedWaveProvider != null &&
                            _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes <
                            _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            //Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(100);
                        }
                        else
                        {
                            var da = DataAvailable;
                            if (da != null)
                            {
                                Mp3Frame frame;
                                try
                                {
                                    frame = Mp3Frame.LoadFromStream(readFullyStream);
                                }
                                catch (EndOfStreamException)
                                {
                                    // reached the end of the MP3 file / stream
                                    break;
                                }
                                catch (WebException)
                                {
                                    // probably we have aborted download from the GUI thread
                                    break;
                                }
                                if (decompressor == null || _bufferedWaveProvider == 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 waveFormat = new Mp3WaveFormat(frame.SampleRate,
                                                                              frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);

                                    RecordingFormat = new WaveFormat(frame.SampleRate, 16,
                                                                     frame.ChannelMode == ChannelMode.Mono ? 1 : 2);

                                    decompressor          = new AcmMp3FrameDecompressor(waveFormat);
                                    _bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat)
                                    {
                                        BufferDuration = TimeSpan.FromSeconds(5)
                                    };

                                    _sampleChannel = new SampleChannel(_bufferedWaveProvider);
                                    _sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter;
                                }

                                int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);

                                var sampleBuffer = new float[buffer.Length];
                                int read         = _sampleChannel.Read(sampleBuffer, 0, buffer.Length);

                                da(this, new DataAvailableEventArgs((byte[])buffer.Clone(), read));

                                if (Listening)
                                {
                                    WaveOutProvider?.AddSamples(buffer, 0, read);
                                }
                            }
                        }
                    }

                    // 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();
                        decompressor = null;
                    }
                }
            }
            catch (Exception ex)
            {
                _res = ReasonToFinishPlaying.DeviceLost;
                Logger.LogException(ex, "MP3Stream");
            }
            try
            {
                request?.Abort();
            }
            catch { }
            request = null;
            AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res));
            _abort.Close();
        }
Exemple #20
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);
        }
Exemple #21
0
        private void StreamMP3()
        {
            var             webRequest = (HttpWebRequest)WebRequest.Create(_source);
            HttpWebResponse resp       = null;

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                }
                return;
            }
            byte[] 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);
                    while (!_stopEvent.WaitOne(0, false))
                    {
                        if (_bufferedWaveProvider != null && _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes < _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            //Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(100);
                        }
                        else
                        {
                            Mp3Frame frame = null;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                // 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
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                                decompressor = new AcmMp3FrameDecompressor(waveFormat);
                                this._bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat)
                                {
                                    BufferDuration = TimeSpan.FromSeconds(5)
                                };

                                _waveOut = new DirectSoundOut(1000);
                                _waveOut.Init(_bufferedWaveProvider);
                                _waveOut.Play();
                                _waveOut.PlaybackStopped += wavePlayer_PlaybackStopped;
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                            _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                        if (_stopEvent.WaitOne(0, false))
                        {
                            break;
                        }
                    }
                    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();
                        decompressor = null;
                    }
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
                if (_waveOut != null)
                {
                    _waveOut.Stop();
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Opens MP3 from a stream rather than a file
        /// Will not dispose of this stream itself
        /// </summary>
        /// <param name="inputStream">The incoming stream containing MP3 data</param>
        /// <param name="frameDecompressorBuilder">Factory method to build a frame decompressor</param>
        public Mp3FileReader(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder)
        {
            // Calculated as a double to minimize rounding errors

            mp3Stream = inputStream;
            id3v2Tag = Id3v2Tag.ReadTag(mp3Stream);

            dataStartPosition = mp3Stream.Position;
            var firstFrame = Mp3Frame.LoadFromStream(mp3Stream);
            double bitRate = firstFrame.BitRate;
            xingHeader = XingHeader.LoadXingHeader(firstFrame);
            // If the header exists, we can skip over it when decoding the rest of the file
            if (xingHeader != null) dataStartPosition = mp3Stream.Position;

            // workaround for a longstanding issue with some files failing to load
            // because they report a spurious sample rate change
            var secondFrame = Mp3Frame.LoadFromStream(mp3Stream);
            if (secondFrame != null &&
                (secondFrame.SampleRate != firstFrame.SampleRate ||
                secondFrame.ChannelMode != firstFrame.ChannelMode))
            {
                // assume that the first frame was some kind of VBR/LAME header that we failed to recognise properly
                dataStartPosition = secondFrame.FileOffset;
                // forget about the first frame, the second one is the first one we really care about
                firstFrame = secondFrame;
            }

            this.mp3DataLength = mp3Stream.Length - dataStartPosition;

            // try for an ID3v1 tag as well
            mp3Stream.Position = mp3Stream.Length - 128;
            byte[] tag = new byte[128];
            mp3Stream.Read(tag, 0, 128);
            if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
            {
                id3v1Tag = tag;
                this.mp3DataLength -= 128;
            }

            mp3Stream.Position = dataStartPosition;

            // create a temporary MP3 format before we know the real bitrate
            this.Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate, firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int)bitRate);

            CreateTableOfContents();
            this.tocIndex = 0;

            // [Bit rate in Kilobits/sec] = [Length in kbits] / [time in seconds]
            //                            = [Length in bits ] / [time in milliseconds]

            // Note: in audio, 1 kilobit = 1000 bits.
            bitRate = (mp3DataLength * 8.0 / TotalSeconds());

            mp3Stream.Position = dataStartPosition;

            // now we know the real bitrate we can create an accurate
            this.Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate, firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int)bitRate);
            decompressor = frameDecompressorBuilder(Mp3WaveFormat);
            this.waveFormat = decompressor.OutputFormat;
            this.bytesPerSample = (decompressor.OutputFormat.BitsPerSample) / 8 * decompressor.OutputFormat.Channels;
            // no MP3 frames have more than 1152 samples in them
            // some MP3s I seem to get double
            this.decompressBuffer = new byte[1152 * bytesPerSample * 2];
        }
Exemple #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();
                }
            }
        }
Exemple #24
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();
            }
        }
Exemple #25
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);
            }
        }
Exemple #26
0
		/// <summary>
		/// Opens MP3 from a stream rather than a file
		/// Will not dispose of this stream itself
		/// </summary>
		/// <param name="inputStream"></param>
		public Mp3FileReader(Stream inputStream)
		{
			// Calculated as a double to minimize rounding errors
			double bitRate;

			mp3Stream = inputStream;
			id3v2Tag = Id3v2Tag.ReadTag(mp3Stream);

			dataStartPosition = mp3Stream.Position;
			var mp3Frame = new Mp3Frame(mp3Stream);
			sampleRate = mp3Frame.SampleRate;
			frameLengthInBytes = mp3Frame.FrameLength;
			bitRate = mp3Frame.BitRate;
			xingHeader = XingHeader.LoadXingHeader(mp3Frame);
			// If the header exists, we can skip over it when decoding the rest of the file
			if (xingHeader != null) dataStartPosition = mp3Stream.Position;

			mp3DataLength = mp3Stream.Length - dataStartPosition;

			// try for an ID3v1 tag as well
			mp3Stream.Position = mp3Stream.Length - 128;
			var tag = new byte[128];
			mp3Stream.Read(tag, 0, 3);
			if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
			{
				id3v1Tag = tag;
				mp3DataLength -= 128;
			}

			mp3Stream.Position = dataStartPosition;

			CreateTableOfContents();
			tocIndex = 0;

			// [Bit rate in Kilobits/sec] = [Length in kbits] / [time in seconds] 
			//                            = [Length in bits ] / [time in milliseconds]

			// Note: in audio, 1 kilobit = 1000 bits.
			bitRate = (mp3DataLength*8.0/TotalSeconds());

			mp3Stream.Position = dataStartPosition;

			Mp3WaveFormat = new Mp3WaveFormat(sampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frameLengthInBytes,
			                                  (int) bitRate);
			decompressor = new AcmMp3FrameDecompressor(Mp3WaveFormat); // new DmoMp3FrameDecompressor(this.Mp3WaveFormat); 
			waveFormat = decompressor.OutputFormat;
			bytesPerSample = (decompressor.OutputFormat.BitsPerSample)/8*decompressor.OutputFormat.Channels;
			// no MP3 frames have more than 1152 samples in them
			// some MP3s I seem to get double
			decompressBuffer = new byte[1152*bytesPerSample*2];
		}
Exemple #27
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);
        }
Exemple #28
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();
            }
        }
Exemple #29
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();
                }
            }
        }
Exemple #30
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);
 }
Exemple #31
0
        //got helps from erszcz on stackoverflow
        static void Main(string[] args)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening

            var buffer = new byte[16384 * 4];

            client.Connect(ep);
            client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);
            // send data


            BufferedWaveProvider bufferedWaveProvider = null;
            WaveOut waveOut = new WaveOut();
            IMp3FrameDecompressor decomp = null;

            int count = 0;

            // then receive data
            do
            {
                var receivedData = client.Receive(ref ep);
                Console.WriteLine("receive data from " + ep.ToString());
                client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);
                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;
                    waveOut.Init(bufferedWaveProvider);
                    // allow us to get well ahead of ourselves
                    //this.bufferedWaveProvider.BufferedDuration = 250;
                }
                if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 4)
                {
                    waveOut.Play();
                }
                int decompressed = decomp.DecompressFrame(frame, buffer, 0);

                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);


                count++;
            } while (bufferedWaveProvider.BufferedDuration.TotalSeconds < 18);



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

            //PlayMp3FromUrl(receivedData);
            Console.Read();
        }
Exemple #32
0
        protected Mp3FileReaderBase(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder, bool ownInputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }
            if (frameDecompressorBuilder == null)
            {
                throw new ArgumentNullException(nameof(frameDecompressorBuilder));
            }
            this._ownInputStream = ownInputStream;
            try
            {
                _mp3Stream = inputStream;
                Id3v2Tag   = Id3v2Tag.ReadTag(_mp3Stream);

                _dataStartPosition = _mp3Stream.Position;
                var firstFrame = Mp3Frame.LoadFromStream(_mp3Stream);
                if (firstFrame == null)
                {
                    throw new InvalidDataException("Invalid MP3 file - no MP3 Frames Detected");
                }
                double bitRate = firstFrame.BitRate;
                XingHeader = XingHeader.LoadXingHeader(firstFrame);
                // If the header exists, we can skip over it when decoding the rest of the file
                if (XingHeader != null)
                {
                    _dataStartPosition = _mp3Stream.Position;
                }

                // workaround for a longstanding issue with some files failing to load
                // because they report a spurious sample rate change
                var secondFrame = Mp3Frame.LoadFromStream(_mp3Stream);
                if (secondFrame != null &&
                    (secondFrame.SampleRate != firstFrame.SampleRate ||
                     secondFrame.ChannelMode != firstFrame.ChannelMode))
                {
                    // assume that the first frame was some kind of VBR/LAME header that we failed to recognise properly
                    _dataStartPosition = secondFrame.FileOffset;
                    // forget about the first frame, the second one is the first one we really care about
                    firstFrame = secondFrame;
                }

                _mp3DataLength = _mp3Stream.Length - _dataStartPosition;

                // try for an ID3v1 tag as well
                _mp3Stream.Position = _mp3Stream.Length - 128;
                byte[] tag = new byte[128];
                _mp3Stream.Read(tag, 0, 128);
                if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
                {
                    Id3v1Tag        = tag;
                    _mp3DataLength -= 128;
                }

                _mp3Stream.Position = _dataStartPosition;

                // create a temporary MP3 format before we know the real bitrate
                Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate,
                                                  firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                  firstFrame.FrameLength, (int)bitRate);

                CreateTableOfContents();
                _tocIndex = 0;

                // [Bit rate in Kilobits/sec] = [Length in kbits] / [time in seconds]
                //                            = [Length in bits ] / [time in milliseconds]

                // Note: in audio, 1 kilobit = 1000 bits.
                // Calculated as a double to minimize rounding errors
                bitRate = (_mp3DataLength * 8.0 / TotalSeconds());

                _mp3Stream.Position = _dataStartPosition;

                // now we know the real bitrate we can create an accurate MP3 WaveFormat
                Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate,
                                                  firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int)bitRate);
                _decompressor   = frameDecompressorBuilder(Mp3WaveFormat);
                WaveFormat      = _decompressor.OutputFormat;
                _bytesPerSample = (_decompressor.OutputFormat.BitsPerSample) / 8 * _decompressor.OutputFormat.Channels;
                // no MP3 frames have more than 1152 samples in them
                _bytesPerDecodedFrame = 1152 * _bytesPerSample;
                // some MP3s I seem to get double
                _decompressBuffer = new byte[_bytesPerDecodedFrame * 2];
            }
            catch (Exception)
            {
                if (ownInputStream)
                {
                    inputStream.Dispose();
                }
                throw;
            }
        }
        public void Stream(string url)
        {
            webRequest = (HttpWebRequest)WebRequest.Create(url + "/;");

            int metaInt = 0; // blocksize of mp3 data

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

            HttpWebResponse resp = null;
            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    //ShowError(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
            {
            }

            decompressor = null;
            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    readFullyStream.metaInt = metaInt;

                    System.Threading.Tasks.Task.Factory.StartNew(() => Thread.Sleep(10000)).ContinueWith(x =>
                        {
                            volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);

                            waveOut = new WaveOut();
                            waveOut.Init(volumeProvider);
                        });

                    do
                    {
                        if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame = null;
                            try
                            {

                                frame = Mp3Frame.LoadFromStream(readFullyStream, true);

                                if (metaInt > 0)
                                    songCallback(readFullyStream.SongName);
                                else
                                    songCallback("No Song Info in Stream...");


                            }
                            catch (EndOfStreamException)
                            {
                                this.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
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                                decompressor = new AcmMp3FrameDecompressor(waveFormat);
                                this.bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                this.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);
                    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
                    Dispose();
                }
            }
            finally
            {
                Dispose();
            }
        }
        private void StreamMP3(object state)
        {
            this.fullyDownloaded = false;
            string url = (string)state;

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

            try
            {
                resp = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    ShowError(e.Message);
                }
                return;
            }
            byte[] 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 (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame = null;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                this.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
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                                decompressor = new AcmMp3FrameDecompressor(waveFormat);
                                this.bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                this.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);
                    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
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Exemple #35
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();
        }