/// <summary> Returns the sample rate of the first frame in the mp3. This is usually constant. </summary>
        public uint GetSampleRate()
        {
            if (sampleRate != null)
            {
                return(sampleRate.GetValueOrDefault());
            }

            using (FileStream fs = File.OpenRead(fileName))
            {
                Mp3Frame frame = Mp3Frame.LoadFromStream(fs);

                if (frame != null)
                {
                    sampleRate = (uint)frame.SampleRate;
                }
            }

            return(sampleRate.GetValueOrDefault());
        }
Example #2
0
        /// <summary>
        /// Reads the next mp3 frame
        /// </summary>
        /// <returns>Next mp3 frame, or null if EOF</returns>
        private Mp3Frame ReadNextFrame(bool readData)
        {
            Mp3Frame frame = null;

            try
            {
                frame = Mp3Frame.LoadFromStream(Mp3Stream, readData);
                if (frame != null)
                {
                    tocIndex++;
                }
            }
            catch (EndOfStreamException)
            {
                // suppress for now - it means we unexpectedly got to the end of the stream
                // half way through
            }
            return(frame);
        }
Example #3
0
        double GetMediaDuration(string MediaFilename)
        {
            double duration = 0.0;

            using (FileStream fs = System.IO.File.OpenRead(MediaFilename))
            {
                Mp3Frame frame = Mp3Frame.LoadFromStream(fs);
                if (frame != null)
                {
                    _sampleFrequency = (uint)frame.SampleRate;
                }
                while (frame != null)
                {
                    duration += (double)frame.SampleCount / (double)frame.SampleRate;

                    frame = Mp3Frame.LoadFromStream(fs);
                }
            }
            return(duration);
        }
Example #4
0
    private static AudioClip LoadFromStream(Stream stream, string audioType)
    {
        WaveStream reader;
        int        initialSampleCount = 0;

        if (audioType == ".wav")
        {
            reader = new WaveFileReader(stream);
        }
        else if (audioType == ".mp3")
        {
            reader = new Mp3FileReader(stream);
            Mp3Frame frame = Mp3Frame.LoadFromStream(stream);
            initialSampleCount = frame.SampleCount * reader.WaveFormat.Channels;
            stream.Seek(0, SeekOrigin.Begin);
        }
        else
        {
            stream.Close();
            return(null);
        }
        ISampleProvider provider = reader.ToSampleProvider();
        long            length   = reader.Length / (reader.WaveFormat.BitsPerSample / 8);

        float[] raw = new float[length];
        try
        {
            provider.Read(raw, 0, (int)length);
        }
        catch (NAudio.MmException)
        {
            return(null);
        }
        float[] data = new float[length + initialSampleCount];
        raw.CopyTo(data, initialSampleCount);
        stream.Close();
        AudioClip newClip = AudioClip.Create("SongAudioClip", data.Length / reader.WaveFormat.Channels, reader.WaveFormat.Channels, reader.WaveFormat.SampleRate, false);

        newClip.SetData(data, 0);
        return(newClip);
    }
        private static Mp3Frame[] StreamToFrames(Stream stream, bool readData = false)
        {
            IEnumerable <Mp3Frame> iterator()
            {
                stream.Position = 0;
                while (stream.Position < stream.Length)
                {
                    Mp3Frame next = null;
                    try { next = Mp3Frame.LoadFromStream(stream, readData); }
                    catch { }
                    if (next != null)
                    {
                        yield return(next);
                    }
                }
            }

            using (stream)
            {
                return(iterator().Skip(1).ToArray());
            }
        }
Example #6
0
        // TODO:

        /*
         * Aside from being untested, this code was proposed for a change on the repository,
         * which was rejected with the excuse of being unnecessary, since the current version
         * already supports correct parsing of the MP3 duration. The original thread where this
         * code was copied from was saying otherwise, needs verification.
         */
        private static double GetMP3Duration(string fileName)
        {
            double duration = 0;

            using (var fs = File.OpenRead(fileName))
            {
                Mp3Frame frame;
                for (LoadFrame(); frame != null; LoadFrame())
                {
                    double toAdd = frame.SampleCount * 2.0 / frame.SampleRate;

                    if (frame.ChannelMode != ChannelMode.Mono)
                    {
                        toAdd *= 2;
                    }

                    duration += toAdd;
                }
                void LoadFrame() => frame = Mp3Frame.LoadFromStream(fs);
            }
            return(duration);
        }
Example #7
0
        /// <summary>
        /// Returns a new <see cref="WaveFormat"/> depending on the file in the memory.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public virtual WaveFormat GetWaveFormat(IFileFromMemoryStream sourceStream)
        {
            WaveFormat    format;
            Mp3Frame      frame    = null;;
            AudioFileType fileType = sourceStream.FilePath.EndsWith(".mp3") ?
                                     AudioFileType.Mp3 :
                                     sourceStream.FilePath.EndsWith(".wav") ?
                                     AudioFileType.Wave :
                                     AudioFileType.Unknown;

            if (fileType == AudioFileType.Mp3)
            {
                int counter = 0;
                while (frame == null)
                {
                    frame = Mp3Frame.LoadFromStream((Stream)sourceStream);
                    Thread.Sleep(50);
                    counter++;
                    if (counter > 100)
                    {
                        throw new ArgumentNullException();
                    }
                }

                format = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                           frame.FrameLength, frame.BitRate);
            }
            else if (fileType == AudioFileType.Wave)
            {
                format = (new WaveFileReader(sourceStream.FilePath)).WaveFormat;
            }
            else
            {
                throw new ArgumentException("The file type is currently unsupported");
            }

            return(format);
        }
Example #8
0
        /* From the specified file name, the media duration of the song is retrieved
         * Allows the calculation of the entire song for ingesting fingerprints and song details */
        public static double getMediaDuration(string fileName)
        {
            double duration = 0.0;

            using (FileStream fs = File.OpenRead(fileName))
            {
                Mp3Frame frame = Mp3Frame.LoadFromStream(fs);
                while (frame != null)
                {
                    if (frame.ChannelMode == ChannelMode.Mono)
                    {
                        duration += (double)frame.SampleCount * 2.0 / (double)frame.SampleRate;
                    }
                    else
                    {
                        duration += (double)frame.SampleCount * 4.0 / (double)frame.SampleRate;
                    }

                    frame = Mp3Frame.LoadFromStream(fs);
                }
            }
            return(duration);
        }
Example #9
0
        private void PublishFromStream()
        {
            while (!_tokenSource.IsCancellationRequested)
            {
                var frame = Mp3Frame.LoadFromStream(_stream);
                if (_decompressor == null)
                {
                    _decompressor = CreateFrameDecompressor(frame);
                }
                var bytesRead = _decompressor.DecompressFrame(frame, _buffer, 0);
                if (bytesRead == 0)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    continue;
                }
                AddSamples(_buffer, 0, bytesRead);
#if DEBUG
                Trace.WriteLine($"Buffered '{Source}' ({BufferedStream.CurrentWriteTime})...");
#endif
            }
#if DEBUG
            Trace.WriteLine($"Stopped reading from '{Source}' ({BufferedStream.CurrentWriteTime}).");
#endif
        }
Example #10
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();
        }
Example #11
0
        private async Task DecompressFrames()
        {
            byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
            do
            {
                try
                {
                    //WaveBuffer getting full, taking a break
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 2)
                    {
                        await Task.Delay(500);
                    }
                    //StreamBuffer empty, taking a break
                    else if (stream.Length < 16384 * 2)
                    {
                        await Task.Delay(500);
                    }
                    else
                    {
                        Mp3Frame frame = Mp3Frame.LoadFromStream(stream);
                        if (frame == null)
                        {
                            continue;
                        }
                        if (decompressor == null)
                        {
                            WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                            decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                            bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                            bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(5); // allow us to get well ahead of ourselves
                        }

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

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

            CleanUpAudio();
        }
Example #12
0
        //------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Provides a pcm stream that can be used to a waveout device (i.e. speakers)
        /// or can write pcm samples to a System.IO.Stream
        /// </summary>
        public void Start()
        {
            //declares
            IMp3FrameDecompressor decompressor = null;
            HttpWebResponse       resp         = null;

            IsActive = true;

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

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

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

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

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

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

                    //write decompressed (pcm) samples to local buffer
                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                    if (IsActive)
                    {
                        //fire event
                        if (OnAudioDataCaptured != null)
                        {
                            OnAudioDataCaptured(this, new AudioEventArgs(buffer, decompressed));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugEx.TraceError(ex.Message);
            }
        }
        private void Stream2Mp3(object state)
        {
            try
            {
                fullyDownloaded2 = false;
                var url = (string)state;
                requisicaodaweb2           = (HttpWebRequest)WebRequest.Create(url);
                requisicaodaweb2.UserAgent = "GabardoHost GET URL";
                HttpWebResponse resp;
                try
                {
                    resp = (HttpWebResponse)requisicaodaweb2.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.RequestCanceled)
                    {
                        ShowError(e.Message + e.StackTrace);
                    }
                    return;
                }
                var buffer2 = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

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

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Log.Info("Connected");
            }
            catch (WebException e)
            {
                Log.Error($"Could not read stream: {e.Message}");
                Environment.Exit(1);
            }

            using (var responseStream = response.GetResponseStream())
            {
                var sampleBuffer         = new float[SampleBufferSize];
                var recorders            = new List <DispatchMessageRecorder>();
                var byteBuffer           = new byte[16384 * 4];
                var readFullyStream      = new ReadFullyStream(responseStream);
                var decompressor         = CreateDecompressor(readFullyStream);
                var bufferedWaveProvider = CreateBufferedWaveProvider(decompressor);
                var toneDetector         = new TonePatternDetector(TargetFrequency1, TargetFrequency2,
                                                                   bufferedWaveProvider.WaveFormat.SampleRate);
                var sampleProvider = bufferedWaveProvider.ToSampleProvider();

                while (true)
                {
                    var frame          = Mp3Frame.LoadFromStream(readFullyStream);
                    var bytesReadCount = decompressor.DecompressFrame(frame, byteBuffer, 0);
                    bufferedWaveProvider.AddSamples(byteBuffer, 0, bytesReadCount);
                    var sampleCount = sampleProvider.Read(sampleBuffer, 0, sampleBuffer.Length);

                    if (EndOfSamples(sampleCount, sampleBuffer))
                    {
                        break;
                    }

                    if (toneDetector.Detected(sampleBuffer))
                    {
                        Log.Info($"Tone detected at {DateTime.UtcNow}");
                        recorders.Add(new DispatchMessageRecorder(bufferedWaveProvider.WaveFormat));
                        toneDetector.Reset();
                    }

                    foreach (var recorder in recorders)
                    {
                        recorder.Record(byteBuffer, bytesReadCount, sampleBuffer, sampleCount);
                    }

                    recorders = RefreshRecorderList(recorders).ToList();
                }

                recorders.ForEach(r => r.Dispose());

                var    cli     = new WebClient();
                string apicall = cli.DownloadString("http://api.citizensmedical.ca/ping.php?file=dispatch_" + { DateTime.Now: ddMMyyyy_HHmmssff } +".wav");
                Log.Info("API Results: " + apicall);
                Log.Info("End of stream");
            }
        }
Example #16
0
        private void StreamMp3(object state)
        {
            if (Settings.IgnoreSSLcertificateError)
            {
                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
                }
                else
                {
                    ServicePointManager.ServerCertificateValidationCallback = null;
                }
            }

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

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

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

            IMp3FrameDecompressor decompressor = null;

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

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

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

            var buffer = new byte[16384 * 4];

            IMp3FrameDecompressor decompressor = null;

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

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

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

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

                    volumeProvider        = new VolumeWaveProvider16(bufferedWaveProvider);
                    volumeProvider.Volume = 1.0f;
                    waveOut.Init(volumeProvider);
                    waveOut.Volume = volume;
                    waveOut.Play();
                }
            }
        }
Example #19
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);
            }
        }
Example #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);
        }
Example #21
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();
        }
Example #22
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;
            }
        }
        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();
                }
            }
        }
        private void _bufferLoop()
        {
            Console.WriteLine("[Buffering thread] Started.");
            _wavebuffer.DiscardOnBufferOverflow = true;

            // Buffering loop
            do
            {
                if (_cancel_buffer.IsCancellationRequested)
                {
                    Console.WriteLine("[Buffering thread] Cancellation requested.");
                    //_cancel_buffer_token.ThrowIfCancellationRequested();
                    //Console.WriteLine("[Buffering thread] WARNING: Cancellation token is not cleanly set!");
                    break;
                }

                // Checking metadata
                if (Metadata != stream.Metadata)
                {
                    this.Metadata = stream.Metadata;
                    Task.Factory.StartNew(() =>
                    {
                        Console.WriteLine("[Buffering thread] Metadata has been changed to \"{0}\"", stream.Metadata);
                        Console.WriteLine("[Buffering thread] Delaying because of the buffering...", stream.Metadata);
                        Thread.Sleep(_wavebuffer.BufferedDuration);
                        Console.WriteLine("[Buffering thread] Exposing metadata NOW.", stream.Metadata);
                        if (MetadataChanged != null)
                        {
                            MetadataChanged.Invoke(this, new EventArgs());
                        }
                    });
                }

                // Seperated buffer
                long bufferSize = 1024
                                  * (Codec == StreamCodec.MP3 ? 128 : 8); // 128 kB for MP3, 8 kB for OGG/AACplus
                byte[] buffer             = new byte[bufferSize];
                int    decompressedLength = 0;

                switch (Codec)
                {
                case StreamCodec.MP3:
                    // Decompress the frame
                    decompressedLength = _decoderMp3.DecompressFrame(frame, buffer, 0);

                    // Read next frame
                    frame = Mp3Frame.LoadFromStream(stream);

                    // Add the decompressed frame (samples) into the audio buffer for later playback
                    _wavebuffer.AddSamples(buffer, 0, decompressedLength);
                    break;

                default:
                    throw new NotSupportedException();
                }
            } while (true);

            _decoderMp3.Dispose();
            stream.Close();
            stream.Dispose();
        }
Example #25
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();
                }
            }
        }
Example #26
0
        private void StreamMp3(object nothing)
        {
            if (frameInputStream == null)
            {
                frameInputStream = new MemoryStream(1024 * 1024); //1MB
            }
            readFullyStream = new ReadFullyStream(frameInputStream);
            Mp3Frame frame;

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

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

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

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


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

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

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

                            Monitor.PulseAll(setMediaLock);
                        }
                    }
                }
                else
                {
                    if (playState == PlayState.playing && playDuration >= totalMilliseconds / 1000)
                    {
                        playState = PlayState.mediaEnded;
                        stop();
                    }
                    Thread.Sleep(50);
                }
            }
        }
Example #27
0
        private void StreamMp3(object state)
        {
            fullyDownloaded = false;
            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();
                }
            }
        }
Example #28
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();
                }
            }
        }
        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();
                }
            }
        }
Example #30
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();
            }
        }