/// <summary>
        /// Decompress a single frame of MP3
        /// </summary>
        public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset)
        {
            // 1. copy into our DMO's input buffer
            inputMediaBuffer.LoadData(frame.RawData, frame.FrameLength);

            if (reposition)
            {
                mp3Decoder.MediaObject.Flush();
                reposition = false;
            }

            // 2. Give the input buffer to the DMO to process
            mp3Decoder.MediaObject.ProcessInput(0, inputMediaBuffer, DmoInputDataBufferFlags.None, 0, 0);

            outputBuffer.MediaBuffer.SetLength(0);
            outputBuffer.StatusFlags = DmoOutputDataBufferFlags.None;

            // 3. Now ask the DMO for some output data
            mp3Decoder.MediaObject.ProcessOutput(DmoProcessOutputFlags.None, 1, new[] { outputBuffer });

            if (outputBuffer.Length == 0)
            {
                Debug.WriteLine("ResamplerDmoStream.Read: No output data available");
                return 0;
            }

            // 5. Now get the data out of the output buffer
            outputBuffer.RetrieveData(dest, destOffset);
            Debug.Assert(!outputBuffer.MoreDataAvailable, "have not implemented more data available yet");
            
            return outputBuffer.Length;
        }
예제 #2
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;
            Mp3Frame 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;

            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, 3);
            if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
            {
                id3v1Tag = tag;
                this.mp3DataLength -= 128;
            }

            mp3Stream.Position = dataStartPosition;

            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;

            this.Mp3WaveFormat = new Mp3WaveFormat(sampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frameLengthInBytes, (int)bitRate);
            decompressor = new AcmMp3FrameDecompressor(this.Mp3WaveFormat); // new DmoMp3FrameDecompressor(this.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];
        }
예제 #3
0
        public void FailsToParseInvalidFrame(int length)
        {
            MemoryStream ms = new MemoryStream(new byte[length]);

            Assert.Throws <EndOfStreamException>(() => { Mp3Frame frame = new Mp3Frame(ms); });
        }
예제 #4
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)
                {
                    Debug.Log(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)
                        {
                            Debug.Log("Buffer getting full, taking a break");
                            Thread.Sleep(1000);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                                if (metaInt > 0)
                                {
                                    readFullyStream.StreamTitleChanged += ReadFullyStream_StreamTitleChanged;
                                }
                                else
                                {
                                    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(20) // 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);
                    Debug.Log("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();
                }
            }
        }
예제 #5
0
 public Mp3FrameInfo(Mp3Frame frame, double averageVolume)
 {
     this.Frame     = frame;
     _averageVolume = averageVolume;
 }
예제 #6
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();
            }
        }
예제 #7
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();
                }
            }
        }
예제 #8
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 Mp3Reader(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }
            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;
                }

                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.
                // 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
                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
                this.bytesPerDecodedFrame = 1152 * bytesPerSample;
                // some MP3s I seem to get double
                this.decompressBuffer = new byte[this.bytesPerDecodedFrame * 2];

                this.TableCreater          = new Thread(this.CreateTableBackground);
                this.TableCreater.Priority = ThreadPriority.Highest;
                this.TableCreater.Start();
            }
            catch (Exception)
            {
                if (ownInputStream)
                {
                    inputStream.Dispose();
                }
                throw;
            }
        }
예제 #9
0
        public void Split(List <Song> songs, string folderPath, string mp3Path)
        {
            try
            {
                #region Get FPS by total frames
                //double totalFrames = 0;
                //TimeSpan ts;
                //using (Mp3FileReader reader = new Mp3FileReader(@mp3Path))
                //{
                //    ts = reader.TotalTime;
                //    Mp3Frame mp3Frame = reader.ReadNextFrame();
                //    while (mp3Frame != null)
                //    {
                //        totalFrames++;
                //        mp3Frame = reader.ReadNextFrame();
                //    }
                //}
                //double fps = totalFrames / ts.TotalSeconds;
                #endregion

                double framesPerSecond = 0;
                using (Mp3FileReader reader = new Mp3FileReader(@mp3Path))
                {
                    Mp3Frame mp3Frame = reader.ReadNextFrame();
                    framesPerSecond = Convert.ToDouble(mp3Frame.SampleRate) / Convert.ToDouble(mp3Frame.SampleCount);
                }

                foreach (Song s in songs)
                {
                    s.StartFrames = s.StartSeconds * framesPerSecond;
                }

                for (int i = 0; i < songs.Count; i++)
                {
                    using (Mp3FileReader reader = new Mp3FileReader(@mp3Path))
                    {
                        string track      = songs[i].TrackNumber > 9 ? songs[i].TrackNumber.ToString() : "0" + songs[i].TrackNumber.ToString();
                        string cleanTitle = Path.GetInvalidFileNameChars().Aggregate(songs[i].Name, (current, c) => current.Replace(c.ToString(), String.Empty));
                        songs[i].Path = String.Format("{0}\\{1} {2}.mp3", folderPath, track, cleanTitle);
                        int        count    = 0;
                        Mp3Frame   mp3Frame = reader.ReadNextFrame();
                        FileStream fs       = new FileStream(@songs[i].Path, FileMode.Create, FileAccess.Write);

                        while (mp3Frame != null)
                        {
                            if (songs[i].StartFrames <= count && i == songs.Count - 1)
                            {
                                fs.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);
                            }

                            else if (songs[i].StartFrames <= count && songs[i + 1].StartFrames > count)
                            {
                                fs.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);
                            }

                            mp3Frame = reader.ReadNextFrame();
                            count++;
                        }

                        fs.Close();
                    }
                }

                int n = 0;
                foreach (Song s in songs)
                {
                    n++;
                    using (var meta = TagLib.File.Create(@s.Path))
                    {
                        SaveMp3(meta, s, true);
                    }
                    while (iTunes.ConvertOperationStatus != null)
                    {
                    }
                    if (s.Converted == true)
                    {
                        File.Delete(@s.Path);
                    }
                }

                File.Delete(@mp3Path);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
예제 #10
0
        void PlayerThread()
        {
            MusicFile file = null;

            while (true)
            {
                do
                {
                    queue.TryDequeue(out file);
                    Thread.Sleep(2);
                } while (file == null);
                if (OnFileListUpdate != null)
                {
                    OnFileListUpdate.Invoke(queue.ToList());
                }
                file.Open();
                Mp3Frame frame = file.GetFrame();
                while (frame != null)
                {
                    foreach (Stream output in outputStreams.Keys)
                    {
                        try
                        {
                            output.Write(frame.RawData, 0, frame.RawData.Length);
                            output.Flush();
                        }
                        catch
                        {
                            output.Close();
                            Disattach(output);
                        }
                    }

                    foreach (BinaryWriter writer in outputWriters.Keys)
                    {
                        try
                        {
                            writer.Write(frame.RawData);
                            //writer.Write(frame.RawData, 0, frame.RawData.Length);
                            writer.Flush();
                        }
                        catch (Exception e)
                        {
                            writer.Close();
                            Disattach(writer);
                        }
                    }

                    frame = file.GetFrame();

                    if (OnStatusUpdate != null)
                    {
                        OnStatusUpdate.Invoke(new MusicPlayerStatus()
                        {
                            CurrentFile = file,
                            Connections = outputStreams.Count,
                            Queue       = queue.ToList()
                        });
                    }

                    while (Pause)
                    {
                        Thread.Sleep(2);
                    }
                }
            }
        }
예제 #11
0
        private void CutMP3()
        {
            while (true)
            {
                // Check if all threads need to be stopped
                if (StopCurrentThread())
                {
                    return;
                }

                if (ActiveStatus == 4)
                {
                    break;
                }

                System.Threading.Thread.Sleep(1);
            }

            TimeSpan totalTime = new TimeSpan();
            Mp3Frame frame     = null;


            Mp3FileReader reader = new Mp3FileReader(workingDir + "\\export\\totalmp3\\output.mp3");

            if (multi)
            {
                this.CreateDirectoryIfNotExists(outputDir);

                for (int i = 0; i < fragmenten.Count; i++)
                {
                    if (fragmenten[i].Liedje.FileContent == null)
                    {
                        continue;
                    }

                    // Create a frame stream to write to
                    FileStream file = new FileStream(outputDir + "\\" + (i + 1).ToString("00") + " - " + fragmenten[i].Liedje.Artiest + " - " + fragmenten[i].Liedje.Titel + ".mp3", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                    // Write the last frame of the previous song if it is available
                    if (frame != null)
                    {
                        file.Write(frame.RawData, 0, frame.RawData.Length);
                    }

                    //
                    TimeSpan d = fragmenten[i].EindTijd - fragmenten[i].BeginTijd;
                    if (!fragmenten[i].FadeInBinnen)
                    {
                        d = d.Add(TimeSpan.FromSeconds((fragmenten[i].FadeIn - new DateTime(2000, 1, 1)).TotalSeconds));
                    }

                    // Continue as long as there are frames available
                    while ((frame = reader.ReadNextFrame()) != null)
                    {
                        if (reader.CurrentTime.TotalSeconds - totalTime.TotalSeconds < d.TotalSeconds)
                        {
                            file.Write(frame.RawData, 0, frame.RawData.Length);
                            frame = null;
                        }
                        else
                        {
                            break;
                        }
                    }

                    totalTime = totalTime.Add(d);

                    this.cutMP3++;
                }
            }
            else
            {
                cutMP3 = totalFragments;
                System.IO.File.Copy(workingDir + "\\export\\totalmp3\\output.mp3", outputDir, true);
            }

            ActiveStatus = 5;
            OnUpdated();


            ActiveStatus = 6;
            OnUpdated();
            MessageBox.Show("De playbackband is klaar!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #12
0
        private void StreamMp3(object state)
        {
            // Store that we don't have the stream downloaded
            FullyDownloaded = false;
            // Store the URL
            string URL = (string)state;

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

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

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

            // Remove the Decompressor
            IMp3FrameDecompressor Decompressor = null;

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

            int           frame_span_ms = 200;
            Mp3FileReader reader        = new Mp3FileReader(mp3_source);
            int           duration      = Converter.Mp3Duration(reader);

            Mp3Frame frame = reader.ReadNextFrame();
            Dictionary <double, double> milisecond_average = new Dictionary <double, double>();

            while (frame != null)
            {
                Stream stream = new MemoryStream();
                double start  = (reader.CurrentTime).TotalMilliseconds;
                double span   = 0;

                while (frame != null && (span < frame_span_ms || (duration - start) <= frame_span_ms * 2))
                {
                    stream.Write(frame.RawData, 0, frame.RawData.Length);
                    frame = reader.ReadNextFrame();

                    if (frame == null)
                    {
                        break;
                    }

                    span = ((reader.CurrentTime).TotalMilliseconds - start);
                }

                stream.Position = 0;

                WaveStream pcm  = Converter.Mp3ToWAV(stream);
                byte[]     data = WaveStreamToArray(pcm);
                double[]   fft_result;

                Converter.Process16bitWAV(ref data, out fft_result, true);

                double ave = fft_result.Average();

                milisecond_average.Add(start + frame_span_ms, ave);
                stream.Close();
            }

            /* double[] keys = milisecond_average.Keys.ToArray();
             * for (int i = 0; i < keys.Length;i++)
             *   if (milisecond_average[keys[i]] <= 0)
             *       milisecond_average.Remove(keys[i]);*/



            int[] indexesOfMinimaParts = AsmodatMath.AMath.GetSplitIndexesMinima(milisecond_average.Values.ToArray(), parts);

            if (indexesOfMinimaParts == null)
            {
                return(null);
            }

            List <int> results = new List <int>();

            for (int i = 0; i < indexesOfMinimaParts.Length; i++)
            {
                int    idx    = indexesOfMinimaParts[i];
                double rezult = milisecond_average.Keys.ToArray()[idx];

                if (i % 2 == 0)
                {
                    results.Add((int)rezult);
                }
                else
                {
                    results.Add((int)(rezult + (double)((double)frame_span_ms / 2)));
                }
            }

            return(results.ToArray());
        }
예제 #14
0
        //double min_speech_duration = 500,
        public static int[] GetMp3SilenceSplit(string mp3_source, double fftdb_silence_treshold = 5, int parts_max = int.MaxValue)
        {
            //string name = Path.GetFileNameWithoutExtension(mp3_source);
            int           frame_span_ms = 200;
            Mp3FileReader reader        = new Mp3FileReader(mp3_source);
            int           duration      = Converter.Mp3Duration(reader);

            Mp3Frame frame = reader.ReadNextFrame();
            Dictionary <double, double> milisecond_average = new Dictionary <double, double>();

            while (frame != null)
            {
                Stream stream = new MemoryStream();
                double start  = (reader.CurrentTime).TotalMilliseconds;
                double span   = 0;

                while (frame != null && (span < frame_span_ms || (duration - start) <= frame_span_ms * 2))
                {
                    // currentTime = (reader.CurrentTime).TotalMilliseconds;
                    stream.Write(frame.RawData, 0, frame.RawData.Length);
                    frame = reader.ReadNextFrame();

                    if (frame == null)
                    {
                        break;
                    }

                    span = ((reader.CurrentTime).TotalMilliseconds - start);
                }

                stream.Position = 0;

                WaveStream pcm  = Converter.Mp3ToWAV(stream);
                byte[]     data = WaveStreamToArray(pcm);
                double[]   left, right;

                //silence = 0
                //whisper = 15
                //conversation = 60
                Converter.Process16bitWAV(ref data, out left, out right, true);

                double aveL = left.Average();
                double aveR = right.Average();


                milisecond_average.Add(start + frame_span_ms, (double)(aveL + aveR) / 2);
                stream.Close();
            }



            var                      kvp_array          = milisecond_average.ToArray();
            int                      counter            = 0;
            List <double>            counter_list       = new List <double>();
            Dictionary <double, int> milisecond_counter = new Dictionary <double, int>();
            int                      counter_parts      = 0;

            for (int i = 0; i < kvp_array.Length; i++)
            {
                double key   = kvp_array[i].Key;
                double value = kvp_array[i].Value;

                if (value > fftdb_silence_treshold)
                {
                    ++counter;
                    counter_list.Add(key);
                }

                if (counter_list.Count > 0)
                {
                    foreach (double k in counter_list)
                    {
                        if (milisecond_counter.ContainsKey(k))
                        {
                            milisecond_counter[k] = counter;
                        }
                        else
                        {
                            milisecond_counter.Add(k, counter);
                        }
                    }
                }


                if (value <= fftdb_silence_treshold)
                {
                    if (counter > 0)
                    {
                        ++counter_parts;
                    }


                    counter = 0;
                    counter_list.Clear();
                    milisecond_counter.Add(key, int.MaxValue);
                }
                else if (i == kvp_array.Length - 1 && counter > 0)
                {
                    ++counter_parts;
                }
            }

            while (counter_parts > parts_max)
            {
                var  kvp   = milisecond_counter.ToArray();
                bool found = false;
                int  min   = milisecond_counter.Values.Min();
                for (int i = 0; i < kvp.Length; i++)
                {
                    double key   = kvp[i].Key;
                    double value = kvp[i].Value;

                    if (found && value != min)
                    {
                        break;
                    }

                    if (!found && value == min)
                    {
                        found = true;
                    }

                    if (!found && value != min)
                    {
                        continue;
                    }

                    milisecond_average.Remove(key);
                    milisecond_counter.Remove(key);
                }

                --counter_parts;
            }



            List <int> list    = new List <int>();
            bool       started = false;

            foreach (var kvp in milisecond_average)
            {
                if (kvp.Value > fftdb_silence_treshold)
                {
                    started = true;
                }

                if (!started)
                {
                    continue;
                }

                if (kvp.Value <= fftdb_silence_treshold)
                {
                    list.Add((int)(kvp.Key + ((double)frame_span_ms / 2)));
                    started = false;
                }
            }



            reader.Close();


            if (!started && list.Count <= 1)
            {
                return(new int[0]);
            }
            else if (!started)
            {
                list.RemoveAt(list.Count - 1);
            }

            if (list.Count > parts_max)//remove smallest parts
            {
            }

            return(list.ToArray());
        }
예제 #15
0
        private static IMp3FrameDecompressor CreateFrameDecompressor(Mp3Frame frame)
        {
            WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);

            return(new AcmMp3FrameDecompressor(waveFormat));
        }
예제 #16
0
 public FoundMp3FrameEventArgs(Mp3Frame mp3Frame)
 {
     this.mp3Frame = mp3Frame;
 }
예제 #17
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 = 0.5f;
                            waveOut.Init(volumeProvider);
                            waveOut.Play();
                        }
                    }
                }
                catch (EndOfStreamException)
                {
                    CleanUpAudio();
                }
            } while (IsPlaying);

            CleanUpAudio();
        }
예제 #18
0
 public static Mp3FrameInfo ToFrameInfo(this Mp3Frame frame, double averageVolume)
 {
     return(new Mp3FrameInfo(frame, averageVolume));
 }
예제 #19
0
        public static void receivingSong()
        {
            waveOut = new WaveOut();
            decomp  = null;

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

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

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

                Mp3Frame frame;
                Stream   ms = new MemoryStream();

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

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



                count++;
            } while (buffering);
        }
예제 #20
0
        /// <summary>
        /// Reads decompressed PCM data from our MP3 file.
        /// </summary>
        public override int Read(byte[] sampleBuffer, int offset, int numBytes)
        {
            int bytesRead = 0;

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

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

                if (repositionedFlag)
                {
                    decompressor.Reset();

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

                    repositionedFlag = false;
                }

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

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

                        int toCopy = Math.Min(decompressed - decompressBufferOffset, numBytes - bytesRead);
                        Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
                        if ((toCopy + decompressBufferOffset) < decompressed)
                        {
                            decompressBufferOffset = toCopy + decompressBufferOffset;
                            decompressLeftovers    = decompressed - decompressBufferOffset;
                        }
                        else
                        {
                            // no lefovers
                            decompressBufferOffset = 0;
                            decompressLeftovers    = 0;
                        }
                        offset    += toCopy;
                        bytesRead += toCopy;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Debug.Assert(bytesRead <= numBytes, "MP3 File Reader read too much");
            position += bytesRead;
            return(bytesRead);
        }
예제 #21
0
        public static void Mp3RemoveSilence(string mp3_source, double fftdb_silence_treshold = 0, int silence_span = 200)
        {
            if (silence_span < 200)
            {
                silence_span = 200;
            }

            int frame_span_ms = silence_span;

            Mp3FileReader reader   = new Mp3FileReader(mp3_source);
            int           duration = Converter.Mp3Duration(reader);

            Mp3Frame frame = reader.ReadNextFrame();
            Dictionary <double, double> milisecond_average = new Dictionary <double, double>();

            string temp_destination = Converter.GetTemporaryFilePath;

            if (File.Exists(temp_destination))
            {
                File.Delete(temp_destination);
            }

            FileStream stream_destination = new FileStream(temp_destination, FileMode.Create, FileAccess.Write);

            byte[] previous_buffer = null;
            bool   started         = false;

            while (frame != null)
            {
                Stream stream = new MemoryStream();
                double start  = (reader.CurrentTime).TotalMilliseconds;
                double span   = 0;

                while (frame != null && (span < frame_span_ms || (duration - start) <= frame_span_ms * 2))
                {
                    // currentTime = (reader.CurrentTime).TotalMilliseconds;
                    stream.Write(frame.RawData, 0, frame.RawData.Length);
                    frame = reader.ReadNextFrame();

                    if (frame == null)
                    {
                        break;
                    }

                    span = ((reader.CurrentTime).TotalMilliseconds - start);
                }


                WaveStream pcm  = Converter.Mp3ToWAV(stream);
                byte[]     data = WaveStreamToArray(pcm);
                double[]   ffr_result;

                //silence = 0
                //whisper = 15
                //conversation = 60
                Converter.Process16bitWAV(ref data, out ffr_result, true);



                double ave = ffr_result.Average();

                if (ave > fftdb_silence_treshold)
                {
                    byte[] buf = Streams.ToArray(stream);

                    if (previous_buffer != null)
                    {
                        stream_destination.Write(previous_buffer, 0, previous_buffer.Length);
                    }

                    stream_destination.Write(buf, 0, buf.Length);
                    previous_buffer = null;
                    started         = true;
                }
                else
                {
                    if (started)
                    {
                        byte[] buf = Streams.ToArray(stream);
                        stream_destination.Write(buf, 0, buf.Length);
                        started = false;
                    }
                    else
                    {
                        previous_buffer = Streams.ToArray(stream);
                    }
                }

                stream.Close();
            }

            stream_destination.Close();
            reader.Close();

            File.Delete(mp3_source);
            File.Copy(temp_destination, mp3_source);
            File.Delete(temp_destination);
        }
예제 #22
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();
                }
            }
        }
예제 #23
0
        public static Stream Mp3RemoveSilence(Stream source, double fftdb_silence_treshold = 0, int silence_span = 200)
        {
            if (source == null)
            {
                return(null);
            }
            if (silence_span < 200)
            {
                silence_span = 200;
            }

            int frame_span_ms = silence_span;

            try
            {
                source.Position = 0;
                Mp3FileReader reader = new Mp3FileReader(source);

                int duration = Converter.Mp3Duration(reader);

                Mp3Frame frame = reader.ReadNextFrame();
                Dictionary <double, double> milisecond_average = new Dictionary <double, double>();

                Stream destination = new MemoryStream();

                byte[] previous_buffer = null;
                bool   started         = false;
                while (frame != null)
                {
                    Stream stream = new MemoryStream();
                    double start  = (reader.CurrentTime).TotalMilliseconds;
                    double span   = 0;

                    while (frame != null && (span < frame_span_ms || (duration - start) <= frame_span_ms * 2))
                    {
                        stream.Write(frame.RawData, 0, frame.RawData.Length);
                        frame = reader.ReadNextFrame();

                        if (frame == null)
                        {
                            break;
                        }

                        span = ((reader.CurrentTime).TotalMilliseconds - start);
                    }


                    WaveStream pcm = Converter.Mp3ToWAV(stream);

                    byte[]   data = WaveStreamToArray(pcm);
                    double[] ffr_result;
                    Converter.Process16bitWAV(ref data, out ffr_result, true);
                    double ave = ffr_result.Average();

                    if (ave > fftdb_silence_treshold)
                    {
                        byte[] buf = Streams.ToArray(stream);

                        if (previous_buffer != null)
                        {
                            destination.Write(previous_buffer, 0, previous_buffer.Length);
                        }

                        destination.Write(buf, 0, buf.Length);
                        previous_buffer = null;
                        started         = true;
                    }
                    else
                    {
                        if (started)
                        {
                            byte[] buf = Streams.ToArray(stream);
                            destination.Write(buf, 0, buf.Length);
                            started = false;
                        }
                        else
                        {
                            previous_buffer = Streams.ToArray(stream);
                        }
                    }

                    stream.Close();
                }

                reader.Close();

                return(destination);
            }
            catch (Exception ex)
            {
                Output.WriteException(ex);
                return(null);
            }
        }
예제 #24
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");
            }
        }
예제 #25
0
            private void StreamMP3_New(object state)
            {
                Thread.CurrentThread.Name = state.ToString();
                string url = (string)state;

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

                Dictionary <int, IMp3FrameDecompressor> Decompressors = new Dictionary <int, IMp3FrameDecompressor>();
                WaveFormat outputFormat = new WaveFormat(44100, 16, 2);

                this.bufferedWaveProvider = new BufferedWaveProvider(outputFormat);
                this.bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(2);

//                WaveToSampleProvider wav2sample = new WaveToSampleProvider(this.bufferedWaveProvider);

                ISampleProvider sampleProvider = new Pcm16BitToSampleProvider(this.bufferedWaveProvider);

                SampleAggregator sa = new SampleAggregator(128);

                sa.NotificationCount = 882;
                sa.PerformFFT        = true;
                sa.FftCalculated    += sa_FftCalculated;
                NotifyingSampleProvider notifyProvider = new NotifyingSampleProvider(sampleProvider);

                notifyProvider.Sample += (a, b) => sa.Add(b.Left);

                volumeProvider = new VolumeSampleProvider(notifyProvider);
                //volumeProvider = new SampleChannel(this.bufferedWaveProvider, true);
                volumeProvider.Volume = 0.0f;
                //volumeProvider.PreVolumeMeter += waveChannel_PreVolumeMeter;

                for (int j = 0; j < 5; ++j)
                {
                    try {
                        using (IWavePlayer waveOut = new WaveOut()) {
                            waveOut.PlaybackStopped += waveOut_PlaybackStopped;
                            waveOut.Init(volumeProvider);

                            using (var readFullyStream = new ShoutcastStream(url)) {
                                waveOut.Play();
                                if (OnStartPlay != null)
                                {
                                    OnStartPlay(this);
                                }

                                do
                                {
                                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                                    {
                                        int x = 0;
                                        while (playbackState != StreamingPlaybackState.Stopped && x < 5)
                                        {
                                            x++;
                                            Thread.Sleep(50);
                                        }
                                    }
                                    else
                                    {
                                        Mp3Frame frame = Mp3Frame.LoadFromStream(readFullyStream, true);

                                        if (currentTrack != readFullyStream.StreamTitle)
                                        {
                                            currentTrack = readFullyStream.StreamTitle;
                                            if (!string.IsNullOrEmpty(currentTrack))
                                            {
                                                ThreadPool.QueueUserWorkItem(Search, currentTrack);
                                            }
                                            else
                                            {
                                                CurrentTrack = null;
                                                if (OnNewTrack != null)
                                                {
                                                    OnNewTrack(this, null);
                                                }
                                            }
                                        }

                                        IMp3FrameDecompressor dec;
                                        if (!Decompressors.TryGetValue(frame.SampleRate, out dec))
                                        {
                                            WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate,
                                                                                      frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                                      frame.FrameLength, frame.BitRate);

                                            var suggFromat = AcmStream.SuggestPcmFormat(waveFormat);

                                            dec = new VbrAcmMp3FrameDecompressor(waveFormat, outputFormat);
                                            Decompressors[frame.SampleRate] = dec;
                                        }


                                        int decompressed = dec.DecompressFrame(frame, buffer, 0);
                                        bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                                    }
                                } while (playbackState != StreamingPlaybackState.Stopped);

                                waveOut.Stop();
                            }
                        }

                        return;
                    } catch (Exception exe) {
                        int x = 0;
                        while (playbackState != StreamingPlaybackState.Stopped && x < 20)
                        {
                            x++;
                            Thread.Sleep(50);
                        }
                        if (playbackState == StreamingPlaybackState.Stopped)
                        {
                            return;
                        }
                    } finally {
                        foreach (var dc in Decompressors)
                        {
                            dc.Value.Dispose();
                        }

                        Decompressors.Clear();
                    }
                }

                if (OnError != null)
                {
                    OnError(this);
                }
            }
예제 #26
0
파일: LameHeader.cs 프로젝트: brson/slush
 public LameHeader(Mp3Frame frame)
 {
     this.frame = frame;
 }
예제 #27
0
        private void StreamMP3()
        {
            HttpWebRequest request = null;

            try
            {
                var resp   = ConnectionFactory.GetResponse(_source, false, 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 (!_stopEvent.WaitOne(10, false) && !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);
                                }
                            }
                        }
                        if (_stopEvent.WaitOne(0, false))
                        {
                            break;
                        }
                    }

                    AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser));

                    // 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)
            {
                var af = AudioFinished;
                af?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost));

                MainForm.LogExceptionToFile(ex, "MP3Stream");
            }
            finally
            {
                try
                {
                    request?.Abort();
                }
                catch { }
                request = null;
            }
        }
예제 #28
0
 public void CanParseValidMp3Frame()
 {
     MemoryStream ms    = new MemoryStream(constructValidMp3Frame());
     Mp3Frame     frame = new Mp3Frame(ms);
 }
예제 #29
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);
            }
        }
예제 #30
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();
                }
            }
        }
예제 #31
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);
                }
            }
        }
예제 #32
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();
            }
        }
예제 #33
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)
                {
                    Log4NetHelper.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())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (IsBufferNearlyFull)
                        {
                            Log4NetHelper.Error("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);
                    Console.WriteLine("Exiting");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor?.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
        private void Stream2Mp3(object state)
        {
            try
            {
                fullyDownloaded2 = false;
                var url = (string)state;
                requisicaodaweb2           = (HttpWebRequest)WebRequest.Create(url);
                requisicaodaweb2.UserAgent = "GabardoHost GET URL";
                HttpWebResponse resp;
                try
                {
                    resp = (HttpWebResponse)requisicaodaweb2.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.RequestCanceled)
                    {
                        ShowError(e.Message + e.StackTrace);
                    }
                    return;
                }
                var buffer2 = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame

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