Exemplo n.º 1
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));
        }
Exemplo n.º 2
0
        public string Describe(string fileName)
        {
            var stringBuilder = new StringBuilder();

            using (var reader = new Mp3FileReader(fileName))
            {
                Mp3WaveFormat wf = reader.Mp3WaveFormat;
                stringBuilder.AppendFormat("MP3 File WaveFormat: {0} {1}Hz {2} channels {3} bits per sample\r\n",
                                           wf.Encoding, wf.SampleRate,
                                           wf.Channels, wf.BitsPerSample);
                stringBuilder.AppendFormat("Extra Size: {0} Block Align: {1} Average Bytes Per Second: {2}\r\n",
                                           wf.ExtraSize, wf.BlockAlign,
                                           wf.AverageBytesPerSecond);
                stringBuilder.AppendFormat("ID: {0} Flags: {1} Block Size: {2} Frames per Block: {3}\r\n",
                                           wf.id, wf.flags, wf.blockSize, wf.framesPerBlock
                                           );

                stringBuilder.AppendFormat("Length: {0} bytes: {1} \r\n", reader.Length, reader.TotalTime);
                stringBuilder.AppendFormat("ID3v1 Tag: {0}\r\n", reader.Id3v1Tag == null ? "None" : reader.Id3v1Tag.ToString());
                stringBuilder.AppendFormat("ID3v2 Tag: {0}\r\n", reader.Id3v2Tag == null ? "None" : reader.Id3v2Tag.ToString());
                Mp3Frame frame;
                while ((frame = reader.ReadNextFrame()) != null)
                {
                    stringBuilder.AppendFormat("{0},{1},{2}Hz,{3},{4}bps, length {5}\r\n",
                                               frame.MpegVersion, frame.MpegLayer,
                                               frame.SampleRate, frame.ChannelMode,
                                               frame.BitRate, frame.FrameLength);
                }
            }
            return(stringBuilder.ToString());
        }
Exemplo n.º 3
0
        protected override void RipLoop(Domain.BufferedStream bufferedStream)
        {
            _currentFrame = Mp3Frame.LoadFromStream(bufferedStream);

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

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

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

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

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

            RaiseFrameDecompressed(_currentFrame, _waveFormat, _decompressor.OutputFormat, _buffer, decompressed);
        }
Exemplo n.º 4
0
        public void CanCreateDmoMp3FrameDecompressor()
        {
            var mp3Format         = new Mp3WaveFormat(44100, 2, 215, 32000);
            var frameDecompressor = new DmoMp3FrameDecompressor(mp3Format);

            Assert.IsNotNull(frameDecompressor);
        }
Exemplo n.º 5
0
        private IMp3FrameDecompressor CreateFrameDecompressor(Mp3Frame Frame)
        {
            WaveFormat WaveFormat = new Mp3WaveFormat(Frame.SampleRate, Frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                      Frame.FrameLength, Frame.BitRate);

            return(new AcmMp3FrameDecompressor(WaveFormat));
        }
Exemplo n.º 6
0
//сохранить выделенный фрагмент
        private void сохранитьВыделенныйФрагментToolStripMenuItem_Click(object sender, EventArgs e) // сохранение фрагмента файла
        {
            String extension = System.IO.Path.GetExtension(openFileDialog1.FileName).ToLower();

            if (extension == ".wav")
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();        // окно выбора пути сохранения
                saveFileDialog1.Filter           = "WAV files (*.wav)|*.wav"; // фильтр
                saveFileDialog1.FilterIndex      = 1;
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    TrimWav(openFileDialog1.FileName, saveFileDialog1.FileName, hScrollBar1.Value, hScrollBar2.Value);
                }
            }
            if (extension == ".mp3")
            {
                string        fileName    = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".mp3"; // создание временного файла
                Mp3FileReader mp3         = new Mp3FileReader(openFileDialog1.FileName);                       // открытие файла в виде потока байтов
                Mp3WaveFormat Format      = mp3.Mp3WaveFormat;                                                 // создание переменной формата с указанием параметров
                var           buffer      = new byte[mp3.Length];                                              // создание массива байтов с длиной равной длине файла
                byte[]        samples     = new byte[buffer.Length];
                int           _bufferSize = Convert.ToInt32(mp3.Length);                                       // переменная, которая содержит длину файла
                var           read        = 0;
                read  = mp3.Read(buffer, 0, buffer.Length);                                                    // чтение файла
                write = new WaveFileWriter(fileName, Format);                                                  // создание файла с указанием пути и формата

                string strMP3Folder = openFileDialog1.FileName;
                int    count        = 1;

                using (Mp3FileReader reader = new Mp3FileReader(strMP3Folder))
                {
                    Mp3Frame mp3Frame = reader.ReadNextFrame();
                    while (mp3Frame != null)
                    {
                        if (count > 250) //retrieve a sample of 500 frames
                        {
                            return;
                        }

                        write.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);
                        count    = count + 1;
                        mp3Frame = reader.ReadNextFrame();
                    }
                }

                write.Close();                                                // закрытие потока записи

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();        // окно выбора пути сохранения
                saveFileDialog1.Filter           = "MP3 files (*.mp3)|*.mp3"; // фильтр
                saveFileDialog1.FilterIndex      = 1;
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.Copy(fileName, saveFileDialog1.FileName, true); // копирование временного файла в место указанное пользователем
                    File.Delete(fileName);                               // удаление временного файла
                }
            }
        }
Exemplo n.º 7
0
        public static void playMusic(UdpClient privatePort, IPEndPoint privateEP)
        {
            string mediaFolder = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "MusicLibrary");

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

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

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

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

                    count1   = count1 + 1;
                    mp3Frame = reader.ReadNextFrame();
                }
                privatePort.Send(Encoding.ASCII.GetBytes("done"), 4, privateEP);
                Console.WriteLine("Total packet sent: " + total);
                Console.WriteLine("------Stop Sending------");
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns an MP3 Frame decompressor from a single frame.
        /// </summary>
        private static IMp3FrameDecompressor CreateFrameDecompressor(Mp3Frame Frame)
        {
            // Create the wave format
            WaveFormat Format = new Mp3WaveFormat(Frame.SampleRate, Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, Frame.FrameLength, Frame.BitRate);

            // And return it as an MP3 frame decompressor
            return(new AcmMp3FrameDecompressor(Format));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Opens MP3 from a stream rather than a file
        /// Will not dispose of this stream itself
        /// </summary>
        /// <param name="inputStream"></param>
        public Mp3FileReader(Stream inputStream)
        {
            // Calculated as a double to minimize rounding errors
            double bitRate;

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

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

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

            mp3DataLength = mp3Stream.Length - dataStartPosition;

            // try for an ID3v1 tag as well
            mp3Stream.Position = mp3Stream.Length - 128;
            var tag = new byte[128];

            mp3Stream.Read(tag, 0, 3);
            if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
            {
                id3v1Tag       = tag;
                mp3DataLength -= 128;
            }

            mp3Stream.Position = dataStartPosition;

            CreateTableOfContents();
            tocIndex = 0;

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

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

            mp3Stream.Position = dataStartPosition;

            Mp3WaveFormat = new Mp3WaveFormat(sampleRate, mp3Frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frameLengthInBytes,
                                              (int)bitRate);
            decompressor   = new AcmMp3FrameDecompressor(Mp3WaveFormat);           // new DmoMp3FrameDecompressor(this.Mp3WaveFormat);
            waveFormat     = decompressor.OutputFormat;
            bytesPerSample = (decompressor.OutputFormat.BitsPerSample) / 8 * decompressor.OutputFormat.Channels;
            // no MP3 frames have more than 1152 samples in them
            // some MP3s I seem to get double
            decompressBuffer = new byte[1152 * bytesPerSample * 2];
        }
Exemplo n.º 10
0
        public void Play()
        {
            byte[] buffer = new byte[RequestConstants.DepressLength]; //[16384 * 4]; // needs to be big enough to hold a decompressed frame
            while (true)
            {
                while (RStream.Length == 0 && (IsPlaying || RStream.Length > PlayNotifySize))
                {
                    IsPlaying = true;
                    //播放流程待优化
                    Mp3Frame frame = null;
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                    {
                        Thread.Sleep(500);
                        continue;
                    }

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

                    if (decompressor == null)
                    {
                        WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                        decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                        bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                        _waveOut.Init(bufferedWaveProvider);
                        _waveOut.Play();
                    }
                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                    bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                }
                if (Stopped)
                {
                    RStream = new MemoryStream();
                    break;
                }
                Thread.Sleep(200);
            }
        }
Exemplo n.º 11
0
        protected override void RipLoopCleanup()
        {
            if (_decompressor != null)
            {
                _decompressor.Dispose();
                _decompressor = null;
            }

            _waveFormat   = null;
            _currentFrame = null;
        }
Exemplo n.º 12
0
        private IMp3FrameDecompressor CreateFrameDeCompressor()
        {
            if (_reader == null)
            {
                throw new ArgumentNullException(nameof(_reader));
            }

            Id3v2Tag.ReadTag(_reader); // read tag data in from begin of stream

            _dataStartPosition = _reader.Position;
            var firstFrame = Mp3Frame.LoadFromStream(_reader);

            if (firstFrame == null)
            {
                throw new InvalidDataException("Invalid MP3 file - no MP3 Frames Detected");
            }
            double bitRate    = firstFrame.BitRate;
            var    xingHeader = XingHeader.LoadXingHeader(firstFrame);

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

            // workaround for a longstanding issue with some files failing to load
            // because they report a spurious sample rate change
            var secondFrame = Mp3Frame.LoadFromStream(_reader);

            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;
            }

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

            var decompressor = new AcmMp3FrameDecompressor(Mp3WaveFormat);

            _decompressBuffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
            MaxPosition       = _reader.Length - _dataStartPosition;
            Duration          = TimeSpan.FromSeconds((double)MaxPosition / Mp3WaveFormat.AverageBytesPerSecond);

            return(decompressor);
        }
Exemplo n.º 13
0
        private int DecompressFrame(Mp3Frame frame, byte[] buffer)
        {
            // decode frame
            if (_decompressor == null)
            {
                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                _decompressor = new AcmMp3FrameDecompressor(waveFormat);

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

                _channels = _waveProvider.WaveFormat.Channels;

                _sampleProvider = _waveProvider.ToSampleProvider();
            }

            return(_decompressor.DecompressFrame(frame, buffer, 0));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns a new <see cref="WaveFormat"/> depending on the file in the memory.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public virtual WaveFormat GetWaveFormat(IFileFromMemoryStream sourceStream)
        {
            WaveFormat    format;
            Mp3Frame      frame    = null;;
            AudioFileType fileType = sourceStream.FilePath.EndsWith(".mp3") ?
                                     AudioFileType.Mp3 :
                                     sourceStream.FilePath.EndsWith(".wav") ?
                                     AudioFileType.Wave :
                                     AudioFileType.Unknown;

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

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

            return(format);
        }
Exemplo n.º 15
0
        public void WindowsMediaMp3DecoderSupportsStereoMp3()
        {
            WaveFormat waveFormat = new Mp3WaveFormat(44100, 2, 0, 32000);

            Assert.IsTrue(IsInputFormatSupported(waveFormat));
        }
Exemplo n.º 16
0
        private void StreamMp3(object state)
        {
            _isBuffering(true);

            ThrottledStream responseStream = (ThrottledStream)state;

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

            IMp3FrameDecompressor decompressor = null;

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

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

                            Mp3Frame frame;

                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);

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

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

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

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

                            if (_bufferedWaveProvider != null)
                            {
                                try
                                {
                                    int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                                    _bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                                }
                                catch (Exception e)
                                {
                                    _fullyDownloaded = true;
                                    _log.Log("Grooveshark: Error decompressing frame: " + e.Message, Category.Exception, Priority.Medium);
                                    break;
                                }
                            }
                        } while (_playbackState != StreamingPlaybackState.Stopped);

                        // was doing this in a finally block, but for some reason
                        // we are hanging on response stream .Dispose so never get there
                        if (decompressor != null)
                        {
                            decompressor.Dispose();
                            decompressor = null;
                        }
                    }
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                    decompressor = null;
                }
            }

            _log.Log("Grooveshark: Buffer thread exiting", Category.Info, Priority.Medium);
        }
Exemplo n.º 17
0
        private void StreamMP3(object state)
        {
            fullyDownloaded = false;
            string url = (string)state;

            webRequest = (HttpWebRequest)WebRequest.Create(url);  //why HttpWebRequest instead of WebRequest
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    throw;
                }
                return;
            }
            byte[] buffer = new byte[16384 * 4]; //how to calc this number?

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (bufferedWaveProvider != null &&
                            bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes <
                            bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            //buffer getting full
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                fullyDownloaded = true; //file or stream reach end
                                break;
                            }
                            catch (WebException)
                            {
                                break;
                            }
                            if (decompressor == null)
                            {
                                WaveFormat format = new Mp3WaveFormat(frame.SampleRate,
                                                                      frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                      frame.FrameLength, frame.BitRate);
                                decompressor         = new AcmMp3FrameDecompressor(format);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat)
                                {
                                    BufferDuration = TimeSpan.FromSeconds(20)
                                };
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Exemplo n.º 18
0
        public static void receivingSong()
        {
            waveOut = new WaveOut();
            decomp  = null;


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

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

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

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

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


                count++;
            } while (buffering);
        }
Exemplo n.º 19
0
        private void StreamMP3()
        {
            _abort = new ManualResetEvent(false);
            HttpWebRequest request = null;

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

                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    while (!_abort.WaitOne(20) && !MainForm.ShuttingDown)
                    {
                        if (_bufferedWaveProvider != null &&
                            _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes <
                            _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            //Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(100);
                        }
                        else
                        {
                            var da = DataAvailable;
                            if (da != null)
                            {
                                Mp3Frame frame;
                                try
                                {
                                    frame = Mp3Frame.LoadFromStream(readFullyStream);
                                }
                                catch (EndOfStreamException)
                                {
                                    // reached the end of the MP3 file / stream
                                    break;
                                }
                                catch (WebException)
                                {
                                    // probably we have aborted download from the GUI thread
                                    break;
                                }
                                if (decompressor == null || _bufferedWaveProvider == null)
                                {
                                    // don't think these details matter too much - just help ACM select the right codec
                                    // however, the buffered provider doesn't know what sample rate it is working at
                                    // until we have a frame
                                    WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate,
                                                                              frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);

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

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

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

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

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

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

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

                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    if (decompressor != null)
                    {
                        decompressor.Dispose();
                        decompressor = null;
                    }
                }
            }
            catch (Exception ex)
            {
                _res = ReasonToFinishPlaying.DeviceLost;
                Logger.LogException(ex, "MP3Stream");
            }
            try
            {
                request?.Abort();
            }
            catch { }
            request = null;
            AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res));
            _abort.Close();
        }
Exemplo n.º 20
0
        private async Task DecompressFrames()
        {
            byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
            do
            {
                try
                {
                    //WaveBuffer getting full, taking a break
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 2)
                    {
                        await Task.Delay(500);
                    }
                    //StreamBuffer empty, taking a break
                    else if (stream.Length < 16384 * 2)
                    {
                        await Task.Delay(500);
                    }
                    else
                    {
                        Mp3Frame frame = Mp3Frame.LoadFromStream(stream);
                        if (frame == null)
                        {
                            continue;
                        }
                        if (decompressor == null)
                        {
                            WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                            decompressor         = new AcmMp3FrameDecompressor(waveFormat);
                            bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                            bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(5); // allow us to get well ahead of ourselves
                        }

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

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

            CleanUpAudio();
        }
Exemplo n.º 21
0
        //got helps from erszcz on stackoverflow
        static void Main(string[] args)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening

            var buffer = new byte[16384 * 4];

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


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

            int count = 0;

            // then receive data
            do
            {
                var receivedData = client.Receive(ref ep);
                Console.WriteLine("receive data from " + ep.ToString());
                client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);
                Mp3Frame frame;
                Stream   ms = new MemoryStream();

                ms.Write(receivedData, 0, receivedData.Length);
                ms.Position = 0;
                frame       = Mp3Frame.LoadFromStream(ms, true);



                if (decomp == null)
                {
                    WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                              frame.FrameLength, frame.BitRate);
                    decomp = new AcmMp3FrameDecompressor(waveFormat);
                    bufferedWaveProvider = new BufferedWaveProvider(decomp.OutputFormat);
                    bufferedWaveProvider.BufferDuration =
                        TimeSpan.FromSeconds(20);
                    //var volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider);
                    //volumeProvider.Volume = 1;
                    waveOut.Init(bufferedWaveProvider);
                    // allow us to get well ahead of ourselves
                    //this.bufferedWaveProvider.BufferedDuration = 250;
                }
                if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 4)
                {
                    waveOut.Play();
                }
                int decompressed = decomp.DecompressFrame(frame, buffer, 0);

                bufferedWaveProvider.AddSamples(buffer, 0, decompressed);


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



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

            //PlayMp3FromUrl(receivedData);
            Console.Read();
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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();
                }
            }
        }
Exemplo n.º 24
0
 public void CanCreateDmoMp3FrameDecompressor()
 {
     Mp3WaveFormat           mp3Format         = new Mp3WaveFormat(44100, 2, 215, 32000);
     DmoMp3FrameDecompressor frameDecompressor = new DmoMp3FrameDecompressor(mp3Format);
 }
Exemplo n.º 25
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)
        {
            // Calculated as a double to minimize rounding errors

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

            dataStartPosition = mp3Stream.Position;
            var    firstFrame = Mp3Frame.LoadFromStream(mp3Stream);
            double bitRate    = firstFrame.BitRate;

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

            // workaround for a longstanding issue with some files failing to load
            // because they report a spurious sample rate change
            var secondFrame = Mp3Frame.LoadFromStream(mp3Stream);

            if (secondFrame != null &&
                (secondFrame.SampleRate != firstFrame.SampleRate ||
                 secondFrame.ChannelMode != firstFrame.ChannelMode))
            {
                // assume that the first frame was some kind of VBR/LAME header that we failed to recognise properly
                dataStartPosition = secondFrame.FileOffset;
                // forget about the first frame, the second one is the first one we really care about
                firstFrame = secondFrame;
            }

            this.mp3DataLength = mp3Stream.Length - dataStartPosition;

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

            mp3Stream.Position = dataStartPosition;

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

            CreateTableOfContents();
            this.tocIndex = 0;

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

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

            mp3Stream.Position = dataStartPosition;

            // now we know the real bitrate we can create an accurate
            this.Mp3WaveFormat  = new Mp3WaveFormat(firstFrame.SampleRate, firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int)bitRate);
            decompressor        = frameDecompressorBuilder(Mp3WaveFormat);
            this.waveFormat     = decompressor.OutputFormat;
            this.bytesPerSample = (decompressor.OutputFormat.BitsPerSample) / 8 * decompressor.OutputFormat.Channels;
            // no MP3 frames have more than 1152 samples in them
            // some MP3s I seem to get double
            this.decompressBuffer = new byte[1152 * bytesPerSample * 2];
        }
Exemplo n.º 26
0
        private void DecompressFrames()
        {
            IMp3FrameDecompressor decompressor = null;
            IWavePlayer           waveOut      = null;

            try
            {
                BufferedWaveProvider bufferedWaveProvider = null;
                var buffer    = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
                var firstLoop = true;

                do
                {
                    //WaveBuffer getting full, taking a break
                    if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                    {
                        Thread.Sleep(500);
                    }
                    //StreamBuffer empty, taking a break
                    else if (stream.Length < 16384 * 2)
                    {
                        Thread.Sleep(500);
                    }
                    else
                    {
                        Mp3Frame frame;
                        try
                        {
                            frame = Mp3Frame.LoadFromStream(stream);
                        }
                        catch (EndOfStreamException)
                        {
                            break;
                        }
                        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)
                            {
                                BufferDuration = TimeSpan.FromSeconds(5)
                            };
                            // allow us to get well ahead of ourselves
                        }
                        var decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                        if (decompressed > 0)
                        {
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }

                        if (firstLoop)
                        {
                            firstLoop = false;
                            waveOut   = CreateWaveOut();
                            if (onWaveProviderCreated != null)
                            {
                                var provider = onWaveProviderCreated(bufferedWaveProvider);
                                waveOut.Init(provider);
                            }
                            waveOut.Play();
                        }
                    }
                } while (IsPlaying);
            }
            finally
            {
                if (waveOut != null)
                {
                    waveOut.Stop();
                    waveOut.Dispose();
                }
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Exemplo n.º 27
0
        protected Mp3FileReaderBase(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder, bool ownInputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }
            if (frameDecompressorBuilder == null)
            {
                throw new ArgumentNullException(nameof(frameDecompressorBuilder));
            }
            this._ownInputStream = ownInputStream;
            try
            {
                _mp3Stream = inputStream;
                Id3v2Tag   = Id3v2Tag.ReadTag(_mp3Stream);

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

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

                _mp3DataLength = _mp3Stream.Length - _dataStartPosition;

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

                _mp3Stream.Position = _dataStartPosition;

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

                CreateTableOfContents();
                _tocIndex = 0;

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

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

                _mp3Stream.Position = _dataStartPosition;

                // now we know the real bitrate we can create an accurate MP3 WaveFormat
                Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate,
                                                  firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int)bitRate);
                _decompressor   = frameDecompressorBuilder(Mp3WaveFormat);
                WaveFormat      = _decompressor.OutputFormat;
                _bytesPerSample = (_decompressor.OutputFormat.BitsPerSample) / 8 * _decompressor.OutputFormat.Channels;
                // no MP3 frames have more than 1152 samples in them
                _bytesPerDecodedFrame = 1152 * _bytesPerSample;
                // some MP3s I seem to get double
                _decompressBuffer = new byte[_bytesPerDecodedFrame * 2];
            }
            catch (Exception)
            {
                if (ownInputStream)
                {
                    inputStream.Dispose();
                }
                throw;
            }
        }
Exemplo n.º 28
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);
                }
            }
Exemplo n.º 29
0
        private void StreamMP3(object state)
        {
            this.fullyDownloaded = false;
            string url = (string)state;

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

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

            IMp3FrameDecompressor decompressor = null;

            try
            {
                using (var responseStream = resp.GetResponseStream())
                {
                    var readFullyStream = new ReadFullyStream(responseStream);
                    do
                    {
                        if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
                        {
                            Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(500);
                        }
                        else
                        {
                            Mp3Frame frame = null;
                            try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);
                            }
                            catch (EndOfStreamException)
                            {
                                this.fullyDownloaded = true;
                                // reached the end of the MP3 file / stream
                                break;
                            }
                            catch (WebException)
                            {
                                // probably we have aborted download from the GUI thread
                                break;
                            }
                            if (decompressor == null)
                            {
                                // don't think these details matter too much - just help ACM select the right codec
                                // however, the buffered provider doesn't know what sample rate it is working at
                                // until we have a frame
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
                                decompressor = new AcmMp3FrameDecompressor(waveFormat);
                                this.bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                this.bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
                                //this.bufferedWaveProvider.BufferedDuration = 250;
                            }
                            int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
                            //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                    Debug.WriteLine("Exiting");
                    // was doing this in a finally block, but for some reason
                    // we are hanging on response stream .Dispose so never get there
                    decompressor.Dispose();
                }
            }
            finally
            {
                if (decompressor != null)
                {
                    decompressor.Dispose();
                }
            }
        }
Exemplo n.º 30
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);
                }
            }
        }