Exemple #1
0
 private void winMain_Closed(object sender, EventArgs e)
 {
     if (backWorker != null)
     {
         backWorker.CancelAsync();
         ww.Close();
         if (stream != 0)
         {
             Bass.BASS_Free();
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Save float buffer as ieefloat wave file
        /// </summary>
        /// <param name="buffer">float array</param>
        /// <param name="outFileName">filename</param>
        /// <param name="targetSampleRate">target samplerate </param>
        public void SaveFile(float[] buffer, string outFileName, int targetSampleRate)
        {
            WaveWriter writer = new WaveWriter(outFileName, 1, targetSampleRate, 32, true);

            writer.Write(buffer, buffer.Length << 2);
            writer.Close();
        }
Exemple #3
0
        public void WriteSamplesToFile(float[] samples, int sampleRate, string destination)
        {
            var waveWriter = new WaveWriter(destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);

            waveWriter.Write(samples, samples.Length * FloatLength);
            waveWriter.Close();
        }
Exemple #4
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (newFormat == IntPtr.Zero)
            {
                MessageBox.Show("Please, specify destination format for converting");
                return;
            }
            string       fileName = tbFile2.Text + ".wav";
            int          size     = ar.Milliseconds2Bytes(1000);
            int          len      = ar.GetLengthInBytes();
            AcmConverter ac       = new AcmConverter(oldFormat, newFormat, false);
            FileStream   fs       = new FileStream(fileName, FileMode.Create);
            WaveWriter   ww       = new WaveWriter(fs, AudioCompressionManager.FormatBytes(newFormat));

            pbConvert.Maximum = len;
            int y = 0;

            while (y < len)
            {
                pbConvert.Value = y;
                byte[] data = ar.ReadDataInBytes(y, size);
                if (data.Length == 0)
                {
                    break;
                }
                y += data.Length;
                byte[] newData = ac.Convert(data);
                ww.WriteData(newData);
            }
            ww.Close();
            ar.Close();
            gbConvert.Enabled  = false;
            btnMakeMp3.Enabled = tbFile2.Text.ToLower().EndsWith(".wav");
            OpenContainingFolder(fileName);
        }
        private void WriteSamplesToWavFile(string pathToFile, int sampleRate, int channels, float[] samples)
        {
            WaveWriter waveWriter = new WaveWriter(pathToFile, channels, sampleRate, 8 * 4, true);

            waveWriter.Write(samples, samples.Length * 4);
            waveWriter.Close();
        }
Exemple #6
0
        /// <summary>
        ///   Recode the file
        /// </summary>
        /// <param name = "fileName">Initial file</param>
        /// <param name = "outFileName">Target file</param>
        /// <param name = "targetSampleRate">Target sample rate</param>
        public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate)
        {
            int      stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            TAG_INFO tags   = new TAG_INFO();

            BassTags.BASS_TAG_GetFromFile(stream, tags);
            int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);

            if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true);
                const int  length     = 5512 * 10 * 4;
                float[]    buffer     = new float[length];
                while (true)
                {
                    int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    waveWriter.Write(buffer, bytesRead);
                }
                waveWriter.Close();
            }
            else
            {
                throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString());
            }
        }
 public void WriteSamplesToFile(float[] samples, int sampleRate, string destination)
 {
     var waveWriter = new WaveWriter(
         destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);
     waveWriter.Write(samples, samples.Length * FloatLength);
     waveWriter.Close();
 }
Exemple #8
0
 /// <summary>
 /// Decode File
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public bool DecodeFile()
 {
     try {
         if (!string.IsNullOrEmpty(CurrentFile))
         {
             _chunkSize = 4096;                          // Set Default Chunk Size
             if (CurrentFile.ToLower().Contains(".mp3")) // Check Mp3
             {
                 if (System.IO.File.Exists(CurrentFile)) // Check File Exists
                 {
                     CurrentFileName = System.IO.Path.GetFileName(CurrentFile);
                     using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) {                  // Create Mp3 Stream
                         _mp3Stream      = mp3Stream;                                               // Set Mp3 Stream
                         _bytes          = new byte[mp3Stream.Length];                              // Set Bytes
                         _totalBytes     = mp3Stream.Length;                                        // Set Total Bytes
                         _numBytesToRead = _totalBytes;                                             // Set Num Bytes to Read
                         _numBytesRead   = 0;                                                       // Set Num Bytes Read to 0
                         using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer
                             _writer = writer;                                                      // Set Writer
                             while (_numBytesToRead > 0)                                            // Loop through Chunks
                             {
                                 if (_chunkSize > _numBytesToRead)                                  // Check Progress isn't greater than remaining bytes
                                 {
                                     _chunkSize = 1;                                                // Check a chunk at a time
                                 }
                                 var t = new Thread(ReadDecodeChunk);
                                 t.Start();
                                 if (!t.Join(1500))
                                 {
                                     t.Abort();           // Oops! We read 1 too many bytes! Lets stop trying, we got everything.
                                     _numBytesToRead = 0; // This should take us out of the loop soon
                                 }
                                 if (_readDecodeResult == 0)
                                 {
                                     break;
                                 }
                                 _numBytesRead   += _readDecodeResult;
                                 _numBytesToRead -= _readDecodeResult;
                                 _percent         = ((int)_numBytesRead * 100 / _totalBytes);
                                 if (PercentChanged != null)
                                 {
                                     PercentChanged(_percent);
                                 }
                             }
                             _writer = null;
                             writer.Close();
                             writer.Dispose();
                         }
                         _numBytesToRead = _bytes.Length;
                         _mp3Stream      = null;
                     }
                 }
             }
         }
         return(true);
     } catch {
         throw;
     }
 }
        public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate)
        {
            const int BitsPerSample = 4 * 8;
            var       waveWriter    = new WaveWriter(pathToFile, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);

            waveWriter.Write(samples, samples.Length * 4);
            waveWriter.Close();
        }
Exemple #10
0
 public void OpenRecorder(object sender, EventArgs e)
 {
     if (ww != null)
     {
         ww.Close();
     }
     ww = new WaveWriter(_stream, recEx.FormatBytes());
     OnChangeState(DictaphoneState.Record);
 }
Exemple #11
0
        private void Save(IntPtr format, byte[] data, string fileName)
        {
            //string fileName = string.Format(@"e:\Down\wav\{0}.wav", name);
            WaveWriter ww = new WaveWriter(File.Create(fileName),
                                           AudioCompressionManager.FormatBytes(format));

            ww.WriteData(data);
            ww.Close();
        }
Exemple #12
0
        private static void Vox2Wav(string voxFile, string wavFile, int samplesPerSec)
        {
            BinaryReader br     = new BinaryReader(File.OpenRead(voxFile));
            IntPtr       format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);
            WaveWriter   ww     = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(format));

            Vox.Vox2Wav(br, ww);
            br.Close();
            ww.Close();
        }
        public MemoryStream getTrack(string track)
        {
            WaveFormat   Format   = new WaveFormat(44100, 16, 2);
            MemoryStream WaveFile = new MemoryStream();

            writer = new WaveWriter(WaveFile, Format);
            drive.ReadTrack(Convert.ToInt32(track), new CdDataReadEventHandler(WriteWaveData), null);
            writer.Close();
            //We recreate the MemoryStream because the above line closes the previous MemoryStream as well as the WaveWriter.
            WaveFile = new MemoryStream(WaveFile.ToArray());
            return(WaveFile);
        }
Exemple #14
0
        public void WriteCdaFileToWavFile(string inCdaFile, string outWavFile, BaseEncoder.ENCODEFILEPROC progressCallback)
        {
            var measuringStream = BassCd.BASS_CD_StreamCreateFile(inCdaFile, BASSFlag.BASS_DEFAULT);

            if (measuringStream == 0)
            {
                return;
            }

            var totalLength = Bass.BASS_ChannelGetLength(measuringStream, BASSMode.BASS_POS_BYTES);

            Bass.BASS_StreamFree(measuringStream);

            var stream = BassCd.BASS_CD_StreamCreateFile(inCdaFile, BASSFlag.BASS_STREAM_DECODE);

            if (stream == 0)
            {
                return;
            }

            try
            {
                var ww   = new WaveWriter(outWavFile, stream, true);
                var data = new short[32768];

                var bytesSoFar = 0;

                while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING)
                {
                    var length = Bass.BASS_ChannelGetData(stream, data, 32768);

                    if (length > 0)
                    {
                        ww.Write(data, length);

                        bytesSoFar += length;

                        progressCallback.Invoke(totalLength, bytesSoFar);
                    }
                }

                // finilize the wave file!
                ww.Close();
                Bass.BASS_StreamFree(stream);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error copying cda file '{0}' to wav file '{1}'", inCdaFile, outWavFile), ex);
            }
        }
Exemple #15
0
        private byte[] PcmToWav(int file)
        {
            WaveFormat wf = GetWaveFormat();

            FormatDetails[] fdArr  = AudioCompressionManager.GetFormatList(wf);
            IntPtr          format = fdArr[0].FormatHandle;
            MemoryStream    ms     = new MemoryStream();
            WaveWriter      ww     = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));

            ww.WriteData(files[file]);
            ww.Close();
            byte[] wav = ms.GetBuffer();
            ms.Close();
            return(wav);
        }
Exemple #16
0
        void rex_Close(object sender, EventArgs e)
        {
            AudioWaveWriter.Close();
            AudioWaveWriter = null;

            string Mp3FileName = AudioFileName.Replace(".wav", ".ria");

            ConvertToMp3(AudioFileName, Mp3FileName);

            if (this.OnRecordingIsDone != null)
            {
                this.OnRecordingIsDone(Mp3FileName);
            }
            AudioFileName     = "";
            this.is_recording = false;
        }
Exemple #17
0
 private void buttonSaveAs_Click(object sender, System.EventArgs e)
 {
     if (listViewTracks.SelectedIndices.Count > 0)
     {
         int    ndx   = listViewTracks.SelectedIndices[0];
         string title = string.Format("track{0:00}", ndx + 1);
         saveFileDialog.FileName = string.Format("{0}.wav", title);
         if (saveFileDialog.ShowDialog() == DialogResult.OK)
         {
             ripping = true;
             try
             {
                 statusBar.Text = string.Format("Reading track {0}", ndx + 1);
                 UpdateVisualControls();
                 IntPtr     format = CdDrive.GetFormat();
                 WaveWriter ww     = new WaveWriter(File.Create(saveFileDialog.FileName),
                                                    AudioCompressionManager.FormatBytes(format));
                 CdReader cr           = cda.GetReader(ndx);
                 int      durationInMS = cr.GetDurationInMS();
                 int      max          = durationInMS / 1000;
                 progressBar1.Minimum = 0;
                 progressBar1.Value   = 0;
                 progressBar1.Maximum = max + 1;
                 for (int i = 0; i <= max; i++)
                 {
                     byte[] data = cr.ReadData(i, 1);
                     ww.WriteData(data);
                     progressBar1.Value = i + 1;
                     Application.DoEvents();
                 }
                 cr.Close();
                 ww.Close();
                 DsConvert.ToWma(saveFileDialog.FileName, saveFileDialog.FileName + ".wma",
                                 DsConvert.WmaProfile.Stereo128);
             }
             finally
             {
                 ripping = false;
             }
         }
     }
     UpdateVisualControls();
 }
Exemple #18
0
        public bool ConvertToWAV(string inPath, string outPath, uint sampleRate, uint sampleSize, uint channels)
        {
            WaveLib.WaveFormat fmt = new WaveLib.WaveFormat((int)sampleRate, (int)sampleSize, (int)channels);
            using (WmaStream str = new WmaStream(inPath, fmt)) {
                byte[] buffer = new byte[str.SampleSize * 2];

                AudioWriter writer = new WaveWriter(new FileStream(outPath, FileMode.Create), str.Format);
                try {
                    int read;
                    while ((read = str.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        writer.Write(buffer, 0, read);
                    }
                }
                finally {
                    writer.Close();
                }
            } //str.Close() is automatically called by Dispose.

            return(true);
        }
Exemple #19
0
        /// <summary>
        /// We get an event with 1 second of data (PCM 44100hz)
        /// </summary>
        private void IceCastStreamUpdate(object sender, StreamUpdateEventArgs data)
        {
            dtLastEvent = DateTime.Now;

            if (audioSample == null)
            {
                audioSample = new float[44100 * 2 * 15];
                audioOffset = 0;
            }

            int len = data.Data.Length;

            if (audioOffset + len > audioSample.Length)
            {
                len = audioSample.Length - audioOffset;
            }

            Buffer.BlockCopy(data.Data, 0, audioSample, audioOffset * 4, len * 4);
            audioOffset += len;

            if (audioOffset == audioSample.Length)
            {
                // Write wav file to disk
                if (doWriteChunksToWAVFile)
                {
                    string     filename = string.Format("{0}-{1:yyyy-MM-dd}#{1:HHmmss}#.wav", radioName, DateTime.Now);
                    WaveWriter ww       = new WaveWriter(filename, 2, 44100, 16, true);
                    ww.Write(audioSample, audioSample.Length * 4);
                    ww.Close();
                    //ww.Dispose(); // this removes the file
                }

                DetectAudio(audioSample, 44100, 2);
                audioSample = null;
                audioOffset = 0;
            }
        }
    public static void ExportWAV(string srcPath, string destPath, ExportOptions exportOptions)
    {
        Debug.Log("Exporting " + srcPath + " to " + destPath);
        int stream = Bass.BASS_StreamCreateFile(srcPath, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT);

        if (stream == 0 || Bass.BASS_ErrorGetCode() != BASSError.BASS_OK)
        {
            throw new Exception(Bass.BASS_ErrorGetCode().ToString());
        }

        WaveWriter ww = new WaveWriter(destPath, stream, true);

        float[] data = new float[32768];
        while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING)
        {
            // get the sample data as float values as well
            int length = Bass.BASS_ChannelGetData(stream, data, 32768);
            // and write the data to the wave file
            if (length > 0)
            {
                ww.Write(data, length);
            }
        }

        ww.Close();
        Bass.BASS_StreamFree(stream);

        /*
         * const int WAV_HEADER_LENGTH = 44;
         *
         *
         *
         * FileStream ifs = null;
         * BinaryReader br = null;
         *
         * FileStream ofs = null;
         * BinaryWriter bw = null;
         *
         * try
         * {
         *  ifs = new FileStream(srcPath, FileMode.Open, FileAccess.Read);
         *  br = new BinaryReader(ifs);
         *
         *  ofs = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write);
         *  bw = new BinaryWriter(ofs);
         *
         *  ifs.Seek(0, SeekOrigin.Begin);
         *
         *  byte[] header = br.ReadBytes(WAV_HEADER_LENGTH);
         *
         *  ifs.Seek(4, SeekOrigin.Begin);
         *  int chunkLength = br.ReadInt32(); // bytes 4 to 7
         *
         *  ifs.Seek(16, SeekOrigin.Current);
         *  int frequency = br.ReadInt32();
         *  int byterate = br.ReadInt32();
         *
         *  ifs.Seek(WAV_HEADER_LENGTH, SeekOrigin.Begin);
         *  byte[] chunk = br.ReadBytes(chunkLength);
         *
         *
         * }
         * catch
         * {
         *  Debug.LogError("Error with writing wav file");
         * }
         * finally
         * {
         *  try { br.Close(); }
         *  catch { }
         *
         *  try { ifs.Close(); }
         *  catch { }
         *
         *  try { bw.Close(); }
         *  catch { }
         *
         *  try { ofs.Close(); }
         *  catch { }
         * }
         */
    }
Exemple #21
0
 private void btnConvert_Click(object sender, EventArgs e)
 {
     if (newFormat == IntPtr.Zero)
     {
         MessageBox.Show("Please, specify destination format for converting");
         return;
     }
     string fileName = tbFile2.Text + ".wav";
     int size = ar.Milliseconds2Bytes(1000);
     int len = ar.GetLengthInBytes();
     AcmConverter ac = new AcmConverter(oldFormat, newFormat, false);
     FileStream fs = new FileStream(fileName, FileMode.Create);
     WaveWriter ww = new WaveWriter(fs, AudioCompressionManager.FormatBytes(newFormat));
     pbConvert.Maximum = len;
     int y = 0;
     while (y < len)
     {
         pbConvert.Value = y;
         byte[] data = ar.ReadDataInBytes(y, size);
         if (data.Length == 0)
         {
             break;
         }
         y += data.Length;
         byte[] newData = ac.Convert(data);
         ww.WriteData(newData);
     }
     ww.Close();
     ar.Close();
     gbConvert.Enabled = false;
     btnMakeMp3.Enabled = tbFile2.Text.ToLower().EndsWith(".wav");
     OpenContainingFolder(fileName);
 }
Exemple #22
0
        private void ConvertToCCITT(String f, String FileName)
        {
            try
            {
                WaveReader newWr      = new WaveReader(File.OpenRead(f));
                IntPtr     oldPcm     = newWr.ReadFormat();
                byte[]     oldPcmData = newWr.ReadData();
                IntPtr     newFormat  = AudioCompressionManager.GetPcmFormat(1, 16, 8000);
                byte[]     newData    = { };

                WaveFormat wf = AudioCompressionManager.GetWaveFormat(oldPcm);

                newWr.Close();

                if (FileName != "0")
                {
                    f = FileName;
                }

                if (File.Exists(textBox1.Text + Path.GetFileName(f)))
                {
                    File.Delete(textBox1.Text + Path.GetFileName(f));
                }

                // **** debug ****
                //txtStatus.Text += f + eol;

                int samp = wf.nSamplesPerSec;
                int bps  = wf.wBitsPerSample;

                // sample rate is > 8000
                if (samp > 8000)
                {
                    newData = AudioCompressionManager.Resample(oldPcm, oldPcmData, newFormat);
                }

                IntPtr     ccittOut  = AudioCompressionManager.GetCompatibleFormat(newFormat, AudioCompressionManager.MuLawFormatTag);
                byte[]     finalData = AudioCompressionManager.Convert(newFormat, ccittOut, newData, false);
                WaveWriter finalWr   = new WaveWriter(File.Create(textBox1.Text + Path.GetFileName(f)),
                                                      AudioCompressionManager.FormatBytes(ccittOut));

                finalWr.WriteData(finalData);
                finalWr.Close();

                // **** debug *****
                //TextOps(dirUlaw + Path.GetFileName(f) + eol2);

                //DeleteFile(f);
            }
            catch (NullReferenceException nex)
            {
                //TextOps("NullReferenceException: " + nex.Message.ToString() + cr);
            }
            catch (IOException iex)
            {
                //TextOps("IOException: " + iex.Message.ToString() + cr);
            }
            catch (AudioException ex)
            {
                //TextOps("AudioException: " + ex.Message.ToString() + cr);
            }
        }
Exemple #23
0
 /// <summary>
 ///   Recode the file
 /// </summary>
 /// <param name = "fileName">Initial file</param>
 /// <param name = "outFileName">Target file</param>
 /// <param name = "targetSampleRate">Target sample rate</param>
 public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate)
 {
     int stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
     TAG_INFO tags = new TAG_INFO();
     BassTags.BASS_TAG_GetFromFile(stream, tags);
     int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
     if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
     {
         WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true);
         const int length = 5512*10*4;
         float[] buffer = new float[length];
         while (true)
         {
             int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length);
             if (bytesRead == 0)
                 break;
             waveWriter.Write(buffer, bytesRead);
         }
         waveWriter.Close();
     }
     else
         throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString());
 }
        public void RecodeFileToMonoWave(string pathToFile, string outputPathToFile, int targetSampleRate)
        {
            int stream = Bass.BASS_StreamCreateFile(pathToFile, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            TAG_INFO tags = new TAG_INFO();
            BassTags.BASS_TAG_GetFromFile(stream, tags);
            int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            WaveWriter waveWriter = new WaveWriter(outputPathToFile, mixerStream, true);
            const int Length = 5512 * 10 * 4;
            float[] buffer = new float[Length];
            while (true)
            {
                int bytesRead = Bass.BASS_ChannelGetData(mixerStream, buffer, Length);
                if (bytesRead == 0)
                {
                    break;
                }

                waveWriter.Write(buffer, bytesRead);
            }

            waveWriter.Close();
        }
Exemple #25
0
        private static string[] SplitAudio(string fileName, double[] segments, string prefix, string outputDirectory)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (segments == null)
            {
                throw new ArgumentNullException("segments");
            }
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (outputDirectory == null)
            {
                throw new ArgumentNullException("outputDirectory");
            }
            int i = Bass.BASS_StreamCreateFile(fileName, 0, 0,
                                               BASSFlag.BASS_STREAM_PRESCAN | BASSFlag.BASS_STREAM_DECODE);

            if (i == 0)
            {
                throw new InvalidOperationException("Couldn't create stream");
            }

            double sum = segments.Sum();

            long   length  = Bass.BASS_ChannelGetLength(i);
            double seconds = Bass.BASS_ChannelBytes2Seconds(i, length);

            if (sum > seconds)
            {
                throw new ArgumentOutOfRangeException("segments", "Required segments exceed file duration");
            }
            BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(i);

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            int index = 0;
            var list  = new List <string>();

            foreach (double segment in segments)
            {
                double d             = segment;
                long   seconds2Bytes = Bass.BASS_ChannelSeconds2Bytes(i, d);
                var    buffer        = new byte[seconds2Bytes];
                int    getData       = Bass.BASS_ChannelGetData(i, buffer, buffer.Length);
                string name          = string.Format("{0}_{1}.wav", prefix, index);
                string combine       = Path.Combine(outputDirectory, name);
                int    bitsPerSample = info.Is8bit ? 8 : info.Is32bit ? 32 : 16;
                var    waveWriter    = new WaveWriter(combine, info.chans, info.freq, bitsPerSample, true);
                waveWriter.WriteNoConvert(buffer, buffer.Length);
                waveWriter.Close();
                list.Add(combine);
                index++;
            }
            bool free = Bass.BASS_StreamFree(i);

            return(list.ToArray());
        }
Exemple #26
0
        void backWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.ComponentModel.BackgroundWorker b = sender as System.ComponentModel.BackgroundWorker;
            int samples = 32;

            short[] buffer = new short[samples];
            bw = new BinaryWriter(File.Open(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Code.huf", FileMode.Create));

            stream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_STREAM_DECODE);

            ww = new WaveWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/HufSound.wav", stream, true);
            int  mult = 0;
            long len  = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTES);

            while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING)
            {
                int length = Bass.BASS_ChannelGetData(stream, buffer, samples * 2);
                mult++;
                b.ReportProgress((int)(((samples * mult) * 100) / len * 2));
                List <short> listBuffer = new List <short>();
                HuffmanTree  tree       = new HuffmanTree();
                if (length > 0)
                {
                    listBuffer.AddRange(buffer);
                    short[] auxbuf = new short[buffer.Length];
                    auxbuf = buffer;
                    canvasWavComp.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new Action(delegate
                    {
                        //Whole Wave
                        //double xScale = canvasWavComp.Width / samples;

                        //Formula by Manuel García. Dude you're amazing.
                        //NOTE: multiply by 2 'cos I supoused some relation with Nyquist Theorem
                        double xScale = (canvasWavComp.Width * samples) / len * 2;

                        double yScale      = (canvasWavComp.Height / (double)(amplitude * 2)) * ((double)amplitude / MAX_AMP);
                        Polyline graphLine = new Polyline();

                        //This Line is used to move on the x axis
                        Canvas.SetLeft(graphLine, xAxis);

                        graphLine.Stroke          = new SolidColorBrush(Color.FromRgb(244, 67, 54));
                        graphLine.StrokeThickness = 2;
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            graphLine.Points.Add(new Point(xScale * i, (canvasWavComp.Height / 2) - (buffer[i] * yScale)));
                        }
                        xAxis += xScale;
                        //canvasWavComp.Children.Clear();
                        canvasWavComp.Children.Add(graphLine);
                    }));
                    double entaux = 0;
                    foreach (var sym in listBuffer.GroupBy(i => i))
                    {
                        NodeHuf nodeHuf = new NodeHuf();
                        nodeHuf.Symbol    = sym.Key;
                        nodeHuf.Frequency = sym.Count();
                        nodeHuf.Right     = nodeHuf.Left = null;
                        tree.Add(nodeHuf);
                        double prob = (double)nodeHuf.Frequency / samples;
                        //entropy -= prob * (Math.Log(prob) / Math.Log(2));
                        entaux   += prob * Math.Log(1 / (prob), 2);
                        entauxlbl = entaux;
                    }
                    entropy += entaux;
                    entcount++;
                    tree.Build();


                    //Encode
                    System.Collections.BitArray encoded = tree.Encode(auxbuf);
                    byte[] arrayBytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1)];
                    encoded.CopyTo(arrayBytes, 0);
                    File.WriteAllBytes("Compress.bin", arrayBytes);

                    //Decode
                    byte[] data;
                    Stream fs = File.OpenRead("Compress.bin");
                    data = new byte[fs.Length];
                    fs.Read(data, 0, data.Length);
                    System.Collections.BitArray bitDec = new System.Collections.BitArray(data);

                    short[] decoded = tree.Decode(bitDec);
                    if (decoded.Length > 0)
                    {
                        ww.Write(decoded, length);
                    }
                    bw.Write(data);
                    fs.Close();
                }
            }
            //Delete temporaly file
            File.Delete("Compress.bin");

            //Close de Stream WAV ww
            ww.Close();

            //If you not add this line, the backgroundworker will be restat but when file is create again
            //there will be an incongruence because the bw never was closed.
            bw.Close();

            entropy /= entcount;// (len / samples);
            entcount = 0;
        }
        public bool SliceSample()
        {
            Stop();
            int stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_STREAM_DECODE);

            long tLength = Bass.BASS_ChannelGetLength(stream);
            double seconds = (SelectionEnd - SelectionBegin).TotalSeconds;

            /* byte lengths */

            int boffset = (int)Bass.BASS_ChannelSeconds2Bytes(stream, SelectionBegin.TotalSeconds);
            int blength = (int)Bass.BASS_ChannelSeconds2Bytes(stream, seconds);

            Bass.BASS_ChannelSetPosition(stream, boffset, BASSMode.BASS_POS_BYTES);

            BASS_CHANNELINFO info = new BASS_CHANNELINFO();
            Bass.BASS_ChannelGetInfo(stream, info);
            // create the sample
            short[] data = new short[blength]; //, putdata = new byte[blength];
            Bass.BASS_ChannelGetData(stream, data, blength);

            string f = filePath.Substring(0, filePath.LastIndexOf("\\") + 1) + "temp.wav";

            WaveWriter w = new WaveWriter(f, stream, 16, true);
            w.Write(data, blength);
            w.Close();

            return OpenFile(f);
        }
 public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate)
 {
     const int BitsPerSample = 4 * 8;
     var waveWriter = new WaveWriter(pathToFile, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);
     waveWriter.Write(samples, samples.Length * 4);
     waveWriter.Close();
 }
		/// <summary>
		/// Save float buffer as ieefloat wave file
		/// </summary>
		/// <param name="buffer">float array</param>
		/// <param name="outFileName">filename</param>
		/// <param name="targetSampleRate">target samplerate </param>
		public void SaveFile(float[] buffer, string outFileName, int targetSampleRate) {
			WaveWriter writer = new WaveWriter(outFileName, 1, targetSampleRate, 32, true);
			writer.Write(buffer, buffer.Length << 2);
			writer.Close();
		}
Exemple #30
0
 private static void Vox2Wav(string voxFile, string wavFile, int samplesPerSec)
 {
     BinaryReader br = new BinaryReader(File.OpenRead(voxFile));
     IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);
     WaveWriter ww = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(format));
     Vox.Vox2Wav(br, ww);
     br.Close();
     ww.Close();
 }
Exemple #31
0
        // CONVERT TO PCM 8KHz 16-bit mono
        private void ConvertToPcm(String f, String FileName)
        {
            try
            {
                WaveReader wr        = new WaveReader(File.OpenRead(f));
                IntPtr     oldFormat = wr.ReadFormat();
                byte[]     oldData   = wr.ReadData();
                IntPtr     newFormat = AudioCompressionManager.GetPcmFormat(1, 16, 8000);
                byte[]     newData   = { };
                WaveFormat wf        = AudioCompressionManager.GetWaveFormat(oldFormat);

                wr.Close();

                if (FileName != "0")
                {
                    f = FileName;
                }

                if (File.Exists(textBox1.Text + Path.GetFileName(f)))
                {
                    File.Delete(textBox1.Text + Path.GetFileName(f));
                }

                // **** debug ****
                //txtStatus.Text += f + eol;

                int samp = wf.nSamplesPerSec;
                int bps  = wf.wBitsPerSample;

                // sample rate is > 8000
                if (samp > 8000)
                {
                    newData = AudioCompressionManager.Resample(oldFormat, oldData, newFormat);
                    WaveWriter ww = new WaveWriter(File.Create(textBox1.Text + Path.GetFileName(f)),
                                                   AudioCompressionManager.FormatBytes(newFormat));
                    ww.WriteData(newData);
                    ww.Close();

                    // **** debug *****
                    //TextOps(dirPcm + Path.GetFileName(f) + eol2);
                }
                else
                {
                    //TextOps(Path.GetFileName(f) + " already exists at 8KHz" + cr);
                }

                //DeleteFile(f);
            }
            catch (NullReferenceException nex)
            {
                //TextOps("NullReferenceException: " + nex.Message.ToString() + cr);
            }
            catch (IOException iex)
            {
                //TextOps("IOException: " + iex.Message.ToString() + cr);
            }
            catch (AudioException ex)
            {
                //TextOps("AudioException: " + ex.Message.ToString() + cr);
            }
        }
 private void SaveSegment(int segCount, Array testbuf)
 {
     var writer =
         new WaveWriter(
             File.Create(Path.Combine(segmentsFolder,
                                      string.Format("Segment_{0}.wav", segCount.ToString("D3")))),
             new WaveFormatEx(waveOutSamplesPerSecond, 16, 1));
     writer.Write((short[]) testbuf);
     writer.Close();
 }
Exemple #33
0
 /// <summary>
 /// Decode File
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public bool DecodeFile()
 {
     try {
         if (!string.IsNullOrEmpty(CurrentFile)) {
             _chunkSize = 4096; // Set Default Chunk Size
             if (CurrentFile.ToLower().Contains(".mp3")) { // Check Mp3
                 if (System.IO.File.Exists(CurrentFile)) { // Check File Exists
                     CurrentFileName = System.IO.Path.GetFileName(CurrentFile);
                     using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) { // Create Mp3 Stream
                         _mp3Stream = mp3Stream; // Set Mp3 Stream
                         _bytes = new byte[mp3Stream.Length]; // Set Bytes
                         _totalBytes = mp3Stream.Length; // Set Total Bytes
                         _numBytesToRead = _totalBytes; // Set Num Bytes to Read
                         _numBytesRead = 0; // Set Num Bytes Read to 0
                         using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer
                             _writer = writer; // Set Writer
                             while (_numBytesToRead > 0) { // Loop through Chunks
                                 if (_chunkSize > _numBytesToRead) { // Check Progress isn't greater than remaining bytes
                                     _chunkSize = 1; // Check a chunk at a time
                                 }
                                 var t = new Thread(ReadDecodeChunk);
                                 t.Start();
                                 if (!t.Join(1500)) {
                                     t.Abort(); // Oops! We read 1 too many bytes! Lets stop trying, we got everything.
                                     _numBytesToRead = 0; // This should take us out of the loop soon
                                 }
                                 if (_readDecodeResult == 0) {
                                     break;
                                 }
                                 _numBytesRead += _readDecodeResult;
                                 _numBytesToRead -= _readDecodeResult;
                                 _percent = ((int)_numBytesRead * 100 / _totalBytes);
                                 if (PercentChanged != null) {
                                     PercentChanged(_percent);
                                 }
                             }
                             _writer = null;
                             writer.Close();
                             writer.Dispose();
                         }
                         _numBytesToRead = _bytes.Length;
                         _mp3Stream = null;
                     }
                 }
             }
         }
         return true;
     } catch {
         throw;
     }
 }
        public float[] RecordFromMicrophoneToFile(string pathToFile, int sampleRate, int secondsToRecord)
        {
            int stream = Bass.BASS_RecordStart(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT, null, IntPtr.Zero);

            if (stream == 0)
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            int mixerStream = BassMix.BASS_Mixer_StreamCreate(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            if (mixerStream == 0)
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            float[] samples = ReadSamplesFromContinuousMixedStream(sampleRate, secondsToRecord, mixerStream);
            using (WaveWriter waveWriter = new WaveWriter(pathToFile, mixerStream, true))
            {
                waveWriter.Write(samples, samples.Length);
                waveWriter.Close();
            }

            Bass.BASS_StreamFree(mixerStream);
            Bass.BASS_StreamFree(stream);

            return samples;
        }