Read() public method

Reads decompressed PCM data from our MP3 file.
public Read ( byte sampleBuffer, int offset, int numBytes ) : int
sampleBuffer byte
offset int
numBytes int
return int
Esempio n. 1
0
        public double[][] GetNextChunk(int samplesDesired, Mp3FileReader fr, bool fullnormalize = false)
        {
            byte[] buffer = new byte[samplesDesired * 4];
            short[] left = new short[samplesDesired];
            //short[] right = new short[samplesDesired];
            double[] leftd = new double[samplesDesired];
            //double[] rightd = new double[samplesDesired];

            int bytesRead = 0;

            try
            {
                bytesRead = fr.Read(buffer, 0, 4 * samplesDesired);
            }
            catch
            {
                new Exception("An error occurred while reading file");
            }

            int index = 0;
            for (int sample = 0; sample < bytesRead / 4; sample++)
            {
                left[sample] = BitConverter.ToInt16(buffer, index); index += 2;
                //right[sample] = BitConverter.ToInt16(buffer, index);
                index += 2;
            }

            if (fullnormalize)
                leftd = Utilities.NormalizeFull(ref left, left.Length);
            else
                leftd = Utilities.Normalize(ref left, left.Length);

            return new double[][] { leftd, null }; //rightd };
        }
Esempio n. 2
0
 public void CanLoadAndReadVariousProblemMp3Files()
 {
     string testDataFolder = @"C:\Users\Mark\Downloads\NAudio";
     if (!Directory.Exists(testDataFolder))
     {
         Assert.Ignore("{0} not found", testDataFolder);
     }
     foreach (string file in Directory.GetFiles(testDataFolder, "*.mp3"))
     {
         string mp3File = Path.Combine(testDataFolder, file);
         Debug.WriteLine(String.Format("Opening {0}", mp3File));
         using (var reader = new Mp3FileReader(mp3File))
         {
             byte[] buffer = new byte[4096];
             int bytesRead;
             int total = 0;
             do
             {
                 bytesRead = reader.Read(buffer, 0, buffer.Length);
                 total += bytesRead;
             } while (bytesRead > 0);
             Debug.WriteLine(String.Format("Read {0} bytes", total));
         }
     }
 }
Esempio n. 3
0
        public mp3Processor(string file)
        {
            buf = new byte[maxLen];

            WaveStream mp3Reader = new Mp3FileReader(file);
            int read = mp3Reader.Read(buf, 0, buf.Length);
            len = read;
        }
Esempio n. 4
0
 public static byte[] getByteArray(string file, ref int len, ref int channels)
 {
     byte[] buf = new byte[maxLen];
     WaveStream mp3Reader = new Mp3FileReader(file);
     channels = mp3Reader.WaveFormat.Channels;
     int read = mp3Reader.Read(buf, 0, buf.Length);
     len = read;
     return buf;
 }
Esempio n. 5
0
            public bool MakeSnaps(int _snapsize, int _snapcount, string _path, int smooth_size)
            {
                try
                {
                    using (Mp3FileReader pcm = new Mp3FileReader(_path))
                    {
                        int samplesDesired = _snapsize;
                        int blockscount = _snapcount;

                        snap_size = _snapsize;
                        snap_count = _snapcount;
                        total_samples = pcm.Length;
                        length = pcm.TotalTime.Seconds;
                        path = _path;

                        if ((pcm.WaveFormat.SampleRate != 44100) || (pcm.WaveFormat.BitsPerSample != 16))
                            return false;

                        for (int i = 0; i < blockscount; i++)
                        {
                            byte[] buffer = new byte[samplesDesired * 4];
                            short[] left = new short[samplesDesired];
                            short[] right = new short[samplesDesired];
                            double[] leftd = new double[samplesDesired];
                            double[] rightd = new double[samplesDesired];

                            int bytesRead = 0;

                            //for (int j = 0; j < 1; j++) ///////////
                            int seek_counter = 0;
                        seek: pcm.Seek((i + 1) * (i + 1) * (i + 1) * blockscount * samplesDesired % (total_samples - samplesDesired), SeekOrigin.Begin);
                            seek_counter++;

                            bytesRead = pcm.Read(buffer, 0, 4 * samplesDesired);

                            int index = 0;
                            for (int sample = 0; sample < bytesRead / 4; sample++)
                            {
                                left[sample] = BitConverter.ToInt16(buffer, index); index += 2;
                                right[sample] = BitConverter.ToInt16(buffer, index); index += 2;
                            }

                            if (left.Average(t => Math.Abs(t)) == 0)
                                if (seek_counter > 5)
                                    return false;
                                else
                                    goto seek;

                            //snap_log10_energy.Add(Math.Log10(left.Average(t => Math.Abs(t))));

                            leftd = Normalize(left, left.Length);
                            rightd = Normalize(right, right.Length);

                            //alglib.complex[] fl;
                            //alglib.fftr1d(leftd, out fl);
                            //fl[0].x;

                            FourierTransformer ft = new FourierTransformer(samplesDesired);
                            var xxa = new Complex[leftd.Length];

                            for (int j = 0; j < leftd.Length; j++)
                                xxa[j] = new Complex(leftd[j], rightd[j]);

                            var ftt = ft.Transform(xxa);

                            List<double> pow_re_im = new List<double>();
                            //List<double> arg_re_im = new List<double>();

                            ftt.ToList().ForEach(t => pow_re_im.Add(ComplexMath.Abs(t)));
                            //ftt.ToList().ForEach(t => arg_re_im.Add(ComplexMath.Arg(t)));

                            /*if (Double.IsNaN(MC_Log10_Energy(pow_re_im)))
                                if (seek_counter > 5)
                                    return false;
                                else
                                    goto seek;*/

                            fft_snaps.Add(pow_re_im);
                            //fft_smoothed_snaps.Add(Smoothen(pow_re_im, smooth_size));

                            //pow_re_im = Normalize(pow_re_im);

                            /*
                            var f_pwri = pow_re_im.Average(t => Math.Abs(t));
                            for (int k = 0; k < pow_re_im.Count; k++)
                                pow_re_im[k] = (Math.Abs(pow_re_im[k]) >= f_pwri * 1.5) ? pow_re_im[k] : 0;
                            */

                            /*
                            FourierTransformer ft2 = new FourierTransformer(samplesDesired);
                            var xx2 = new List<Complex>();
                            for (int j = 0; j < pow_re_im.Count; j++)
                            {
                                xx2.Add(new Complex(pow_re_im[j], arg_re_im[j]));
                            }
                            var ftt2 = ft2.Transform(xx2);
                            //var ftt2 = ft2.Transform(ftt);

                            List<double> pow_re_im2 = new List<double>();
                            ftt2.ToList().ForEach(t => pow_re_im2.Add(ComplexMath.Abs(t)));
                            pow_re_im2 = Normalize(pow_re_im2);
                            fft2_snaps.Add(pow_re_im2);
                            fft2_smoothed_snaps.Add(Smoothen(pow_re_im2, smooth_size));
                            */
                        }
                        pcm.Close();
                    }
                }
                catch (Exception e)
                {
                return false;
                }

                return true;
            }
        private static byte[] PlayAudioFile(string substring)
        {
            //return File.ReadAllBytes(substring);
            Console.WriteLine("Playing...");
            Stream inputStream = new MemoryStream(File.ReadAllBytes(substring));
            inputStream.Seek(0, SeekOrigin.Begin);
            Stream outputStream = new MemoryStream();
            byte[] bytes = new byte[inputStream.Length];
            string path = @"C:\temp";
            string wavFile = @"C:\temp\tempWav.wav";

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            if (File.Exists(wavFile))
                File.Delete(wavFile);

            using (var reader = new Mp3FileReader(substring))
            {
                using (var writer = new WaveFileWriter(wavFile, new WaveFormat()))
                {
                    var buf = new byte[4096];
                    for (; ; )
                    {
                        var cnt = reader.Read(buf, 0, buf.Length);
                        if (cnt == 0) break;
                        writer.Write(buf, 0, cnt);
                    }
                }
            }

            //SoundPlayer p = new SoundPlayer(wavFile);
            //p.Play();
            return File.ReadAllBytes(wavFile);
        }
Esempio n. 7
0
 /// <summary>
 /// Convert a MP3 file to a Wav file
 /// </summary>
 /// <param name="mp3FilePath"></param>
 /// <param name="wavFilePath"></param>
 public static void ConvertMp3ToWav(string mp3FilePath, string wavFilePath)
 {
     using (var reader = new Mp3FileReader(mp3FilePath)) {
         using (var writer = new WaveFileWriter(wavFilePath, new WaveFormat())) {
             byte[] buffer = new byte[16*1024];
             for (;;) {
                 int bytes = reader.Read(buffer, 0, buffer.Length);
                 if (bytes == 0) break;
                 writer.Write(buffer, 0, bytes);
             }
         }
     }
 }
Esempio n. 8
0
    private void WriteToFile(string SongID, string strPath, byte[] Buffer)
    {
        try
        {
            int  samplesPerPixel = 128;
            long startPosition   = 0;
            //FileStream newFile = new FileStream(GeneralUtils.Get_SongFilePath() + "/" + strPath, FileMode.Create);
            float[] data         = FloatArrayFromByteArray(Buffer);
            Bitmap  bmp          = new Bitmap(1170, 200);
            int     BORDER_WIDTH = 5;
            int     width        = bmp.Width - (2 * BORDER_WIDTH);
            int     height       = bmp.Height - (2 * BORDER_WIDTH);

            NAudio.Wave.Mp3FileReader reader        = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
            NAudio.Wave.WaveChannel32 channelStream = new NAudio.Wave.WaveChannel32(reader);
            int bytesPerSample = (reader.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
                Pen    pen1      = new Pen(Color.Gray);
                int    size      = data.Length;
                string hexValue1 = "#009adf";
                Color  colour1   = System.Drawing.ColorTranslator.FromHtml(hexValue1);
                pen1.Color = colour1;
                Stream wavestream = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
                wavestream.Position = 0;
                int    bytesRead1;
                byte[] waveData1 = new byte[samplesPerPixel * bytesPerSample];
                wavestream.Position = startPosition + (width * bytesPerSample * samplesPerPixel);
                for (float x = 0; x < width; x++)
                {
                    short low  = 0;
                    short high = 0;
                    bytesRead1 = wavestream.Read(waveData1, 0, samplesPerPixel * bytesPerSample);
                    if (bytesRead1 == 0)
                    {
                        break;
                    }
                    for (int n = 0; n < bytesRead1; n += 2)
                    {
                        short sample = BitConverter.ToInt16(waveData1, n);
                        if (sample < low)
                        {
                            low = sample;
                        }
                        if (sample > high)
                        {
                            high = sample;
                        }
                    }
                    float lowPercent  = ((((float)low) - short.MinValue) / ushort.MaxValue);
                    float highPercent = ((((float)high) - short.MinValue) / ushort.MaxValue);
                    float lowValue    = height * lowPercent;
                    float highValue   = height * highPercent;
                    g.DrawLine(pen1, x, lowValue, x, highValue);
                }
            }
            string filename = Server.MapPath("image/060.png");
            bmp.Save(filename);
            bmp.Dispose();
        }
        catch (Exception e)
        {
        }
    }