Exemple #1
0
        public static float[] ConvertWav2FFTMag(string wavfile, string outfile)
        {
            WAVFile audioFile = new WAVFile();
            String  warning   = audioFile.Open(wavfile, WAVFile.WAVFileMode.READ);

            Complex[] indata      = new Complex[MaxSamples];
            int       IterSamples = (audioFile.NumSamples < MaxSamples) ? audioFile.NumSamples : MaxSamples;

            float[] indata_mag = null;

            if (warning == "")
            {
                //short audioSample = 0;
                for (int sampleNum = 0; sampleNum < IterSamples; ++sampleNum)
                {
                    //audioSample = audioFile.GetNextSampleAs16Bit();
                    indata[sampleNum].Re = audioFile.GetNextSampleAs16Bit();
                }
                FourierTransform.FFT(indata, FourierTransform.Direction.Forward);
                indata_mag = GetMagnitude(indata);

                if (outfile != null)
                {
                    WriteData(indata_mag, outfile);
                }
            }
            audioFile.Close();
            return(indata_mag);
        }
Exemple #2
0
        public MemoryStream createWavMemory(Bitmap bitmap, string name, bool create_img, bool with_cue)
        {
            bitmap = managementGUI.resizeImage(bitmap, _scanWidth, _scanHeight, _myEyeMusic.ResizeMode);
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

            float[,] imArr = ReconstructColor(bmpData);
            bitmap.UnlockBits(bmpData);

            if (create_img)
            {
                Bitmap clusteredImage = generatePostClassifictionBitmap(imArr);
                // display image
                _myEyeMusic.setScanPictureBoxes(clusteredImage);
            }

            MemoryStreamEM sonifiedWAV = new MemoryStreamEM();
            MemoryStream   toREt       = sonifiedWAV.Create(_myEyeMusic.OutDirectory + "\\" + name + ".wav", false, 44100, 16);
            double         volume      = _myEyeMusic.MyVolume;

            if (_myEyeMusic.MyCueType.Equals(eyeMusic2.CueType.NoCue))
            {
                volume = 0.0;
            }

            if (with_cue)
            {
                short   sample;
                WAVFile cueWAVFile = new WAVFile();             // adding cue
                cueWAVFile.Open(_myEyeMusic._mapFile + "\\Sounds\\" + _myEyeMusic.model.beep_noise, WAVFile.WAVFileMode.READ);
                for (int j = 0; j < cueWAVFile.NumSamples; j++)
                {
                    sample = (short)(volume * cueWAVFile.GetNextSample_16bit());
                    sample = Math.Min(short.MaxValue, sample);
                    sonifiedWAV.AddSample_16bit(sample);
                }
                cueWAVFile.Close();
            }

            for (int i = 0; i < _scanWidth; i++)
            {
                createMixer(i, sonifiedWAV, imArr);
            }

            sonifiedWAV.addLength();

            toREt = sonifiedWAV.mFileStream;


            return(toREt);
        }
Exemple #3
0
        public void TestMethod1()
        {
            var bg   = BackgroundSound.Instance;
            var wave = new WAVFile();

            wave.Create("dv.wav", false, 8000, 8);

            wave.AddSample_ByteArray(bg.Sounds[2]);

            //var si = new byte[8000 * 5];
            //wave.AddSample_ByteArray(si);
            wave.Close();
        }
        public void StopRecord()
        {
            if (this.PausedTime.HasValue)
            {
                OnResume();
                this.PausedTime = null;
            }

            if (_waveFile != null)
            {
                if (_buffer.Count >= 0)
                {
                    _waveFile.AddSample_ByteArray(_buffer.ToArray());
                }
                _waveFile.Close();
                _waveFile = null;
                _buffer.Clear();
            }
        }
Exemple #5
0
        public static MemoryStream encodeCompressedFromWAV(string source)
        {
            WAVFile      wav = new WAVFile();
            MemoryStream ms  = new MemoryStream();

            wav.Open(source, WAVFile.WAVFileMode.READ);

            IMAADPCM.ADPCMState state = new IMAADPCM.ADPCMState();
            byte enc1, enc2;

            for (long i = 0; i < wav.NumSamples / 2; i++)
            {
                enc1 = IMAADPCM.encodeADPCM(wav.GetNextSampleAs16Bit(), ref state);
                enc2 = IMAADPCM.encodeADPCM(wav.GetNextSampleAs16Bit(), ref state);
                ms.Write(BitConverter.GetBytes(Convert.ToInt32(Utils.binaryString(enc2, 4) + Utils.binaryString(enc1, 4), 2)), 0, 1);
            }

            wav.Close();
            return(ms);
        }
Exemple #6
0
        public float[] GetVPFromWave(string wavefile)
        {
            string w = Path.GetDirectoryName(wavefile) + @"\n_" + Path.GetFileName(wavefile);

            Normalize(wavefile, w);
            WAVFile wave = new WAVFile();

            wave.Open(w, WAVFile.WAVFileMode.READ);
            float[] samples = new float[wave.NumSamples];
            for (int i = 0; i < wave.NumSamples; i++)
            {
                samples[i] = wave.GetNextSample_16bit();
            }

            int cp = 0;
            int t  = samples.Length / 1024;

            if (t > 0)
            {
                int r = samples.Length % 1024;
                for (int x = 1; x <= t; x++)
                {
                    Exocortex.DSP.ComplexF[] complexData = new Exocortex.DSP.ComplexF[1024];
                    for (int i = cp; i <= 1023; i++)
                    {
                        complexData[i].Re = samples[cp + i];
                        complexData[i].Im = samples[cp + i] + 5;
                    }
                    Exocortex.DSP.Fourier.FFT(complexData, complexData.Length, FourierDirection.Forward);
                    for (int i = 0; i <= 1023; i++)
                    {
                        samples[cp + i] = complexData[i].Re;
                    }

                    cp += 1024;
                }
            }

            wave.Close();
            return(samples);
        }
Exemple #7
0
        byte[] GetWavData(string fileName)
        {
            var wav = new WAVFile();

            wav.Open(fileName, WAVFile.WAVFileMode.READ);
            wav.SeekToAudioDataStart();
            byte[] data = new byte[wav.DataSizeBytes];
            byte[] arr;
            int    start = 0;

            do
            {
                arr = wav.GetNextSample_ByteArray();
                arr.CopyTo(data, start);
                start += arr.Length;
            }while (wav.NumSamplesRemaining > 1);

            wav.Close();

            return(data);
        }
Exemple #8
0
        public short[] GetSecondaryVPFromWave(string wavefile)
        {
            //  string w = Path.GetDirectoryName(wavefile) + @"\n_" + Path.GetFileName(wavefile);
            // Normalize(wavefile, w);
            WAVFile wave = new WAVFile();

            wave.Open(wavefile, WAVFile.WAVFileMode.READ);
            short[] samples = new short[wave.NumSamples];
            for (int i = 0; i < wave.NumSamples; i++)
            {
                samples[i] = wave.GetNextSample_16bit();
            }

            int cp = 0;
            int t  = samples.Length / 1024;

            //if (t > 0)
            //{
            //    int r = samples.Length % 1024;
            //    for (int x = 1; x <= t; x++)
            //    {
            //        Exocortex.DSP.ComplexF[] complexData = new Exocortex.DSP.ComplexF[1024];
            //        for (int i = cp; i <= 1023; i++)
            //        {
            //            complexData[i].Re = samples[cp + i];
            //            complexData[i].Im = samples[cp + i] + 5;

            //        }
            //        Exocortex.DSP.Fourier.FFT(complexData, complexData.Length, FourierDirection.Forward);
            //        for (int i = 0; i <= 1023; i++)
            //            samples[cp + i] = complexData[i].Re;

            //        cp += 1024;
            //    }

            //}
            wave.Close();

            return(samples);
        }
Exemple #9
0
        /// <summary>
        /// loads the samples from WavFilePath to _samplesArray
        /// </summary>
        private void loadSamples()
        {
            //WaitForm waitForm = new WaitForm();
            //ProgressBar pb = new ProgressBar();
            //pb.Minimum = 0;

            //WAVFileMP3 currentWAVFile;
            WAVFile currentWAVFile;

            string[] fileNames = Directory.GetFiles(MyFileMap + "\\" + _wavFilePath);
            currentWAVFile = new WAVFile();
            currentWAVFile.Open(fileNames[0], WAVFile.WAVFileMode.READ);
            //pb.Maximum = fileNames.Length * currentWAVFile.NumSamples;
            int seconds = (currentWAVFile.NumSamples - FirstSample);

            currentWAVFile.Close();
            //pb.Value = 0;
            //pb.Location = new Point(40, 80);

            //waitForm.Show();
            //waitForm.Controls.Add(pb);

            Application.DoEvents();
            for (int i = 0; i < fileNames.Length; i++)
            {
                // Create the WAVFile object and open the current sample WAV file.
                currentWAVFile = new WAVFile();
                currentWAVFile.Open(fileNames[i], WAVFile.WAVFileMode.READ);

                // Get the sample from the file and copy it to our array
                for (int j = 0; j < currentWAVFile.NumSamples; j++)
                {
                    _samplesArray[i, j] = currentWAVFile.GetNextSample_16bit();
                }
                //pb.Value += currentWAVFile.NumSamples;
                currentWAVFile.Close();     // Close the WAV file
            }
            //waitForm.Close();
        }
Exemple #10
0
        public static void decodeCompressedToWAV(MemoryStream data, WAVFile target)
        {
            //WAVFile wav = new WAVFile();
            //wav.Create(@"E:\TEMP\SPARKIV\~AudioModding\STARTING_TUNE_LEFT_DECODED.wav", false, 44100, 16, true);

            //FileStream fs = new FileStream(@"E:\TEMP\SPARKIV\~AudioModding\STARTING_TUNE_LEFT.bin", FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[1];

            IMAADPCM.ADPCMState state = new IMAADPCM.ADPCMState();
            short val;

            for (long i = 0; i < data.Length; i++)
            {
                data.Read(buffer, 0, 1);
                val = IMAADPCM.decodeADPCM((byte)(buffer[0] & 0xf), ref state);
                target.AddSample_16bit(val);
                val = IMAADPCM.decodeADPCM((byte)((buffer[0] >> 4) & 0xf), ref state);
                target.AddSample_16bit(val);
            }

            data.Close();
            target.Close();
        }
Exemple #11
0
        //methods for creating wav file

        /// <summary>
        /// allocates an array of according to the number of files in WavFilePath
        /// </summary>
        private void allocateArray()
        {
            int cols, rows;

            string[] fileNames = Directory.GetFiles(MyFileMap + "\\" + _wavFilePath);
            rows = fileNames.Length;

            if (rows != _numTotalFiles)
            {
                throw new System.ArgumentException("total number of files must be equal to the number of files in wav folder");
            }

            // Set the number of cols according to the number samples in the first WAV file
            //WAVFileMP3 tempWAVFile = new WAVFileMP3();
            WAVFile tempWAVFile = new WAVFile();

            tempWAVFile.Open(fileNames[0], WAVFile.WAVFileMode.READ);
            cols = tempWAVFile.NumSamples;
            tempWAVFile.Close();

            // Allocate the array
            _samplesArray = new short[rows, cols];
        }
Exemple #12
0
        /// <summary>
        ///     Store a wavfile generated from the provided sample at the specified location.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="sample"></param>
        private static void StoreWAV(string filename, Sample sample)
        {
            var wav = new WAVFile();

            // TODO: Clamp Sample.BitDepth to 8/16 (or not?)
            wav.Create(filename, false, (int)sample.SampleRate, (short)sample.BitDepth, true);
            if (sample.BitDepth == 8)
            {
                for (int i = 0; i < sample.SampleCount; i++)
                {
                    // Need to add 128 because AddSample_8bit takes unsigned bytes.
                    wav.AddSample_8bit((byte)(sample.ValueAt(i * sample.Resolution) + 128));
                }
            }
            else // Assume 16-bit for now.
            {
                for (int i = 0; i < sample.SampleCount; i++)
                {
                    wav.AddSample_16bit((short)sample.ValueAt(i * sample.Resolution));
                }
            }
            wav.Close();
        }
Exemple #13
0
    // Added by Ali Adams
    public static void GenerateWAVFile(ref string path, List<long> values, int frequency)
    {
        WAVFile wavfile = new WAVFile();
        // update ref path.csv to .wav
        path = path.Substring(0, path.Length - 4) + ".wav";
        wavfile.Create(path, false, frequency, 8);

        Normalize(ref values, 0L, 255L);

        //byte[] bytes = new byte[4 * values.Count];
        //for (int i = 0; i < values.Count; i++)
        //{
        //    int j = 4 * i;
        //    bytes[j + 0] = (byte)(values[i] >>  0 & 0xFF);
        //    bytes[j + 1] = (byte)(values[i] >>  8 & 0xFF);
        //    bytes[j + 2] = (byte)(values[i] >> 16 & 0xFF);
        //    bytes[j + 3] = (byte)(values[i] >> 24 & 0xFF);
        //    wavfile.AddSample_8bit(bytes[j + 0]);
        //    wavfile.AddSample_8bit(bytes[j + 1]);
        //    wavfile.AddSample_8bit(bytes[j + 2]);
        //    wavfile.AddSample_8bit(bytes[j + 3]);
        //}

        byte[] bytes = new byte[values.Count];
        for (int i = 0; i < values.Count; i++)
        {
            wavfile.AddSample_8bit((byte)(values[i]));
        }

        // write the wavefile
        wavfile.Close();
    }
Exemple #14
0
        /// <summary>
        /// Export for use as a wavetable array in c
        /// </summary>
        /// <param name="filename">The completely pathed filename of the file to read</param>
        public static String TableFromWav(string filename)
        {
            ArrayList samples = new ArrayList();

            String ret  = "int [] table = {";
            String suff = "};";

            WAVFile file = new WAVFile();

            String retval = file.Open(filename, WAVFile.WAVFileMode.READ);

            if (retval != "")
            {
                throw new WAVFileException(retval, "WAVFile.Convert_Copy()");
            }

            double dur = (double)file.NumSamples / file.SampleRateHz;

            if (dur > 0.5)
            {
                MessageBox.Show("Wav File too long, please use .wavs less than 1 second long.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return("ERROR");
            }

            int  lastZero   = -1;
            bool hasNonZero = false;
            bool runOfZeros = false;

            while (file.NumSamplesRemaining > 0)
            {
                short sample = file.GetNextSampleAs8Bit();
                if (sample != 0)
                {
                    hasNonZero = true;
                    runOfZeros = false;
                }
                else if (sample == 0 && !runOfZeros)
                {
                    lastZero   = ret.Length;
                    runOfZeros = true;
                }

                if (hasNonZero)
                {
                    ret += sample.ToString();
                    ret += ",";
                }
            }

            file.Close();

            //Remove trailing zeros
            ret = ret.Remove(lastZero, ret.Length - lastZero);
            //Remove trailing comma
            if (ret != null)
            {
                ret = ret.TrimEnd(',');
            }

            return(ret += suff);
        }
Exemple #15
0
        public static bool replaceSample(int sampleIndex, string path)
        {
            long offset = IVAUDSingle.WIoffset[sampleIndex] + IVAUDSingle.headerSize;

            byte[] dataBefore = new byte[offset - IVAUDSingle.headerSize];
            byte[] dataAfter  = new byte[IVAUD.file.Length - (offset + IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex])];

            //Get data between header and replaced sample
            IVAUD.file.Seek(IVAUDSingle.headerSize, SeekOrigin.Begin);
            IVAUD.file.Read(dataBefore, 0, dataBefore.Length);

            //Get data between replaced sample and eof
            IVAUD.file.Seek(offset + IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex], SeekOrigin.Begin);
            IVAUD.file.Read(dataAfter, 0, dataAfter.Length);

            //Close file
            IVAUD.close();

            //Open WAV file and encode it
            WAVFile wav = new WAVFile();

            wav.Open(path, WAVFile.WAVFileMode.READ);

            MemoryStream ms = new MemoryStream();

            IMAADPCM.ADPCMState state = new IMAADPCM.ADPCMState();
            //byte enc1, enc2;

            byte[] bytes     = new byte[2];
            int    loopValue = ((wav.DataSizeBytes - 8) / wav.BytesPerSample);

            /*Debug.WriteLine((((wav.DataSizeBytes - 8) / wav.BytesPerSample)) / 2);
             * Debug.WriteLine(wav.NumSamples / 2);
             * Debug.WriteLine((((wav.DataSizeBytes - 8) / wav.BytesPerSample)));
             * Debug.WriteLine(wav.NumSamples);*/

            //for (long i = 0; i < wav.NumSamples / 2; i++) {
            for (long i = 0; i < loopValue / 2; i++)
            {
                bytes[0] = IMAADPCM.encodeADPCM(wav.GetNextSampleAs16Bit(), ref state);
                bytes[1] = IMAADPCM.encodeADPCM(wav.GetNextSampleAs16Bit(), ref state);
                ms.Write(BitConverter.GetBytes(Convert.ToInt32(Utils.binaryString(bytes[1], 4) + Utils.binaryString(bytes[0], 4), 2)), 0, 1);
            }

            long originalOffset = offset + IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex];

            //Change header values
            IVAUDSingle.WInumSamplesInBytes[sampleIndex]          = (int)ms.Length;
            IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex] = Utils.getPaddedSize(IVAUDSingle.WInumSamplesInBytes[sampleIndex]);
            IVAUDSingle.WInumSamples16Bit[sampleIndex]            = (int)(ms.Length * 2);
            IVAUDSingle.WIsamplerate[sampleIndex] = (ushort)wav.SampleRateHz;
            if (IVAUDSingle.WIHsize[sampleIndex] > 32)
            {
                IVAUDSingle.WInumSamples16Bit2[sampleIndex] = (uint)(ms.Length * 2);
            }

            //Change later offsets
            long newOffset    = offset + IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex];
            long offsetChange = newOffset - originalOffset;

            for (int i = 0; i < IVAUDSingle.WIHoffset.Count; i++)
            {
                if ((IVAUDSingle.WIoffset[i] + IVAUDSingle.headerSize) > offset)
                {
                    IVAUDSingle.WIoffset[i] += offsetChange;
                }
            }

            wav.Close();

            //Get WAV data
            byte[] dataWAV = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(dataWAV, 0, (int)ms.Length);
            ms.Close();

            //Write header
            FileStream fs = new FileStream(Environment.GetEnvironmentVariable("TEMP") + "\\IVATB\\Current" + Utils.sessionID + ".tmp", FileMode.Open, FileAccess.ReadWrite);

            fs.Seek(0, SeekOrigin.Begin);
            if (!IVAUDSingle.write(fs))
            {
                return(false);
            }

            //Write before-data
            fs.Seek(IVAUDSingle.headerSize, SeekOrigin.Begin);
            fs.Write(dataBefore, 0, dataBefore.Length);

            //Write sample
            fs.Seek(offset, SeekOrigin.Begin);
            fs.Write(dataWAV, 0, dataWAV.Length);

            //Write after-data
            fs.Seek(offset + IVAUDSingle.WInumSamplesInBytes_computed[sampleIndex], SeekOrigin.Begin);
            fs.Write(dataAfter, 0, dataAfter.Length);

            //Fix file length if needed
            if (offsetChange < 0)
            {
                fs.SetLength(fs.Length + offsetChange);
            }

            fs.Close();

            //Replace the file
            //IVAUD.close();
            //File.Copy(Environment.GetEnvironmentVariable("TEMP") + "\\IVATB\\Replace" + Utils.sessionID + ".tmp", Environment.GetEnvironmentVariable("TEMP") + "\\IVATB\\Current" + Utils.sessionID + ".tmp", true);

            //Reload the file
            IVAUD.load(Environment.GetEnvironmentVariable("TEMP") + "\\IVATB\\Current" + Utils.sessionID + ".tmp");

            return(true);
        }
Exemple #16
0
    /// <summary>
    /// Changes the volume of a WAV file.
    /// </summary>
    /// <param name="pFilename">The name of the WAV file to adjust</param>
    /// <param name="pMultiplier">The volume multiplier</param>
    public static void AdjustVolumeInPlace(String pFilename, double pMultiplier)
    {
        // If pMultiplier is 1, then we don't need to do anything.
        if (pMultiplier == 1.0)
            return;

        // Open the file
        WAVFile audioFile = new WAVFile();
        String retval = audioFile.Open(pFilename, WAVFileMode.READ_WRITE);
        if (retval.Length == 0)
        {
            // Check to make sure the input file has a supported number of bits/sample and sample rate.  If
            // not, then throw an exception.
            if (!SupportedBitsPerSample(audioFile.BitsPerSample))
            {
                short bitsPerSample = audioFile.BitsPerSample;
                audioFile.Close();
                throw new WAVFileBitsPerSampleException(pFilename + " has unsupported bits/sample ("
                                                        + bitsPerSample.ToString() + ")",
                                                        "WAVFile.AdjustVolumeInPlace()", bitsPerSample);
            }
            if (!SupportedSampleRate(audioFile.SampleRateHz))
            {
                int sampleRate = audioFile.SampleRateHz;
                audioFile.Close();
                throw new WAVFileSampleRateException(pFilename + " has unsupported sample rate ("
                                                     + sampleRate.ToString() + ")",
                                                     "WAVFile.AdjustVolumeInPlace()", sampleRate);
            }

            // Adjust the file volume
            if (audioFile.BitsPerSample == 8)
            {
                byte sample = 0;
                for (int sampleNum = 0; sampleNum < audioFile.NumSamples; ++sampleNum)
                {
                    sample = (byte)((double)audioFile.GetNextSample_8bit() * pMultiplier);
                    audioFile.SeekToAudioSample(sampleNum);
                    audioFile.AddSample_8bit(sample);
                }
            }
            else if (audioFile.BitsPerSample == 16)
            {
                short sample = 0;
                for (int sampleNum = 0; sampleNum < audioFile.NumSamples; ++sampleNum)
                {
                    sample = (short)((double)audioFile.GetNextSample_16bit() * pMultiplier);
                    audioFile.SeekToAudioSample(sampleNum);
                    audioFile.AddSample_16bit(sample);
                }
            }

            audioFile.Close();
        }
        else
            throw new WAVFileReadException(retval, "WAVFile.AdjustVolumeInPlace()");
    }
Exemple #17
0
    /// <summary>
    /// Merges a set of WAV file sinto a single WAV file in such a way that the audio will be overlayed.
    /// This method will throw a WAVFileException upon error.
    /// </summary>
    /// <param name="pFileList">An array containing the audio filenames</param>
    /// <param name="pOutputFilename">The name of the file to contain the resulting audio</param>
    /// <param name="pTempDir">The full path to the temporary directory to use for the work.  If this directory does not exist, it will be created and then deleted when this method no longer needs it.</param>
    public static void MergeAudioFiles(String[] pFileList, String pOutputFilename, String pTempDir)
    {
        // If pFileList is null or empty, then just return.
        if (pFileList == null)
            return;
        if (pFileList.GetLength(0) == 0)
            return;

        // Make sure all the audio files have the sample rate (we can merge 8-bit and 16-bit audio and
        // convert mono to stereo).  If the sample rates don't match, then throw an exception.
        if (!SampleRatesEqual(pFileList))
            throw new WAVFileAudioMergeException("The sample rates of the audio files differ.", "WAVFile.MergeAudioFiles()");

        // Check the audio format.  If the number of bits/sample or sample rate is not
        // supported, then throw an exception.
        WAVFormat firstFileAudioFormat = GetAudioFormat(pFileList[0]);
        if (!SupportedBitsPerSample(firstFileAudioFormat.BitsPerSample))
            throw new WAVFileBitsPerSampleException("Unsupported number of bits per sample: " + firstFileAudioFormat.BitsPerSample.ToString(), "WAVFile.MergeAudioFiles()", firstFileAudioFormat.BitsPerSample);
        if (!SupportedSampleRate(firstFileAudioFormat.SampleRateHz))
            throw new WAVFileSampleRateException("Unsupported sample rate: " + firstFileAudioFormat.SampleRateHz.ToString(), "WAVFile.MergeAudioFiles()", firstFileAudioFormat.SampleRateHz);

        // 2. Create the temporary directory if it doesn't exist already.  This checks for the
        // existence of the temp directory and stores the result in tempDirExisted so that
        // later, if the temp directory did not exist, we can delete it.
        bool tempDirExisted = Directory.Exists(pTempDir);
        if (!tempDirExisted)
        {
            try
            {
                Directory.CreateDirectory(pTempDir);
                if (!Directory.Exists(pTempDir))
                    throw new WAVFileAudioMergeException("Unable to create temporary work directory (" + pTempDir + ")", "WAVFile.MergeAudioFiles()");
            }
            catch (Exception ex)
            {
                throw new WAVFileAudioMergeException("Unable to create temporary work directory (" + pTempDir + "): "
                                                     + ex.Message, "WAVFile.MergeAudioFiles()");
            }
        }

        // 4. Find the highest sample value of all files, and calculate the sound
        //    multiplier based on this (all files will be scaled down by this amount).
        int numTracks = pFileList.GetLength(0);
        double multiplier = 0.0; // The multiplier for scaling down the audio files
        short highestSampleValue = 0; // Will store the highest sample value (8-bit will be cast to short)
        // Determine the highest # of bits per sample in all the audio files.
        short highestBitsPerSample = HighestBitsPerSample(pFileList);
        bool outputStereo = (HighestNumChannels(pFileList) > 1);
        if (highestBitsPerSample == 8)
        {
            // Get the highest sample value of all of the WAV files
            byte highestSample = HighestSampleValue_8bit(pFileList);
            highestSampleValue = (short)highestSample;

            byte difference = (byte)(highestSample - (byte.MaxValue / (byte)numTracks));
            multiplier = 1.0 - ((double)difference / (double)highestSample);
        }
        else if (highestBitsPerSample == 16)
        {
            // Get the highest sample value of all of the WAV files
            highestSampleValue = HighestSampleValueAs16Bit(pFileList);

            short difference = (short)(highestSampleValue - (short.MaxValue / (short)numTracks));
            multiplier = 1.0 - ((double)difference / (double)highestSampleValue);
        }
        if (double.IsInfinity(multiplier) || (multiplier == 0.0))
        {
            // If the temp dir did not exist, then remove it.
            if (!tempDirExisted)
                DeleteDir(pTempDir);
            // Throw the exception
            throw new WAVFileAudioMergeException("Could not calculate first volume multiplier.", "WAVFile.MergeAudioFiles()");
        }

        if (multiplier < 0.0)
            multiplier = -multiplier;

        // 5. Scale down the audio levels of the source files, and save the output
        //    in the temp directory.  Also change the path to the audio files in
        //    inputFilenames so that they point to the temp directory (we'll be
        //    combining the scaled audio files).
        // This array (scaledAudioFiles) will contain WAVFile objects for the scaled audio files.
        WAVFile[] scaledAudioFiles = new WAVFile[pFileList.GetLength(0)];
        String filename = "";               // For the scaled-down WAV filename
        WAVFile inputFile = new WAVFile();
        WAVFile outputFile = new WAVFile();
        for (int i = 0; i < pFileList.GetLength(0); ++i)
        {
            // pFileList[i] contains the fully-pathed filename.  Using just the
            // filename, construct the fully-pathed filename for the scaled-down
            // version of the file in the temporary directory.
            filename = pTempDir + "\\" + Path.GetFileName(pFileList[i]);

            // Copy the file to the temp directory, adjusting its bits/sample and number of
            // channels if necessary.  And also ajust its volume using multiplier.
            CopyAndConvert(pFileList[i], filename, highestBitsPerSample, outputStereo, multiplier);

            // Create the WAVFile object in the scaledAudioFiles array, and open the scaled
            // audio file with it.
            scaledAudioFiles[i] = new WAVFile();
            scaledAudioFiles[i].Open(filename, WAVFileMode.READ);
        }

        // 7. Now, create the final audio mix file.
        outputFile.Create(pOutputFilename, outputStereo, firstFileAudioFormat.SampleRateHz,
                          highestBitsPerSample);

        // 8. Do the merging..
        // The basic algorithm for doing the merging is as follows:
        // while there is at least 1 sample remaining in any of the source files
        //    sample = 0
        //    for each source file
        //       if the source file has any samples remaining
        //          sample = sample + next available sample from the source file
        //    sample = sample / # of source files
        //    write the sample to the output file
        if (highestBitsPerSample == 8)
        {
            byte sample = 0;
            while (SamplesRemain(scaledAudioFiles))
            {
                sample = 0;
                for (int i = 0; i < scaledAudioFiles.GetLength(0); ++i)
                {
                    if (scaledAudioFiles[i].NumSamplesRemaining > 0)
                        sample += scaledAudioFiles[i].GetNextSample_8bit();
                }
                sample /= (byte)(scaledAudioFiles.GetLength(0));
                outputFile.AddSample_8bit(sample);
            }
        }
        else if (highestBitsPerSample == 16)
        {
            short sample = 0;
            while (SamplesRemain(scaledAudioFiles))
            {
                sample = 0;
                for (int i = 0; i < scaledAudioFiles.GetLength(0); ++i)
                {
                    if (scaledAudioFiles[i].NumSamplesRemaining > 0)
                        sample += scaledAudioFiles[i].GetNextSampleAs16Bit();
                }
                sample /= (short)(scaledAudioFiles.GetLength(0));
                outputFile.AddSample_16bit(sample);
            }
        }
        outputFile.Close();

        // 9. Remove the input files(to free up disk space.
        foreach (WAVFile audioFile in scaledAudioFiles)
        {
            filename = audioFile.Filename;
            audioFile.Close();
            File.Delete(filename);
        }

        // 10. Now, increase the volume level of the output file. (will first have
        //     to see if the inputs are 8-bit or 16-bit.)
        //  Adjust the volume level of the file so that its volume is
        //  the same as the volume of the input files.  This is done by
        //  first finding the highest sample value of all files, then
        //  the highest sample value of the combined audio file, and
        //  scaling the audio of the output file to match the volume
        //  of the input files (such that the highest level of the output
        //  file is the same as the highest level of all files).
        // For 16-bit audio, this works okay, but for 8-bit audio, the
        //  output seems to sound better if we adjust the volume so that
        //  the highest sample value is 3/4 of the maximum sample value
        //  for the # of bits/sample.
        if (highestBitsPerSample == 8)
        {
            byte highestSampleVal = WAVFile.HighestSampleValue_8bit(pOutputFilename);
            byte maxValue = byte.MaxValue / 4 * 3;
            multiplier = (double)maxValue / (double)highestSampleVal;
        }
        else if (highestBitsPerSample == 16)
        {
            short finalMixFileHighestSample = WAVFile.HighestSampleValueAs16Bit(pOutputFilename);
            // Calculate the multiplier for adjusting the audio of the final mix file.
            //short difference = (short)(finalMixFileHighestSample - highestSampleValue);
            //multiplier = 1.0 - ((double)difference / (double)finalMixFileHighestSample);
            // This calculates the multiplier based on the highest sample value in the audio
            // file and the highest possible 16-bit sample value.
            multiplier = (double)short.MaxValue / (double)finalMixFileHighestSample;
        }
        if (multiplier < 0.0)
            multiplier = -multiplier;

        // Adjust the volume of the final mix file.
        AdjustVolumeInPlace(pOutputFilename, multiplier);

        // If the temporary directory did not exist prior to this method being called, then
        // delete it.
        if (!tempDirExisted)
        {
            String retval = DeleteDir(pTempDir);
            if (retval.Length > 0)
                throw new WAVFileAudioMergeException("Unable to remove temp directory (" + pTempDir + "): " + retval,
                                                     "WAVFile.MergeAudioFiles()");
        }
    }
Exemple #18
0
    /// <summary>
    /// Returns the highest sample value in a WAV audio file.
    /// The return value is a byte array and will contain one
    /// byte if the file contains 8-bit audio or 2 bytes if the file
    /// contains  16-bit audio.  The return value will be null if
    /// the file cannot be opened.  If it is known that the audio
    /// file contains 16-bit samples, the byte array can be converted
    /// to a 16-bit integer using BitConverter.ToInt16().
    /// </summary>
    /// <param name="pFilename">The name of the WAV file</param>
    /// <param name="pBitsPerSample">This will contain the number of bits per sample, or 0 if the file wasn't loaded.</param>
    /// <returns>A byte array containing the highest audio sample, or null if the file wasn't loaded.</returns>
    public static byte[] HighestSampleValue(String pFilename, out short pBitsPerSample)
    {
        pBitsPerSample = 0;
        byte[] highestSampleValue = null;

        WAVFile audioFile = new WAVFile();
        try
        {
            if (audioFile.Open(pFilename, WAVFileMode.READ).Length == 0)
            {
                pBitsPerSample = audioFile.mBitsPerSample;

                if (audioFile.mBitsPerSample == 8)
                {
                    byte sample = 0;
                    byte highestSample = 0;
                    for (int i = 0; i < audioFile.NumSamples; ++i)
                    {
                        sample = audioFile.GetNextSample_8bit();
                        if (sample > highestSample)
                            highestSample = sample;
                    }

                    highestSampleValue = new byte[1];
                    highestSampleValue[0] = highestSample;
                }
                else if (audioFile.mBitsPerSample == 16)
                {
                    short sample = 0;
                    short highestSample = 0;
                    for (int i = 0; i < audioFile.NumSamples; ++i)
                    {
                        sample = audioFile.GetNextSample_16bit();
                        if (sample > highestSample)
                            highestSample = sample;
                    }

                    highestSampleValue = BitConverter.GetBytes(highestSample);
                    if (!BitConverter.IsLittleEndian)
                        Array.Reverse(highestSampleValue);
                }

                audioFile.Close();
            }
        }
        catch
        {
            // log exception
        }

        return (highestSampleValue);
    }
Exemple #19
0
    /// <summary>
    /// Returns the highest sample value in a WAV file, as a 16-bit value, regardless of
    /// whether the file contains 8-bit or 16-bit audio.  If the sample is coming from
    /// an 8-bit audio file, the sample will be scaled up from 8-bit to 16-bit.
    /// </summary>
    /// <param name="pFilename">The audio file name</param>
    /// <returns>The highest sample value from the file, as a 16-bit value</returns>
    public static short HighestSampleValueAs16Bit(String pFilename)
    {
        short highestSample = 0;

        try
        {
            WAVFile audioFile = new WAVFile();
            if (audioFile.Open(pFilename, WAVFileMode.READ).Length == 0)
            {
                if (audioFile.BitsPerSample == 8)
                {
                    short sample = 0;
                    for (int i = 0; i < audioFile.NumSamples; ++i)
                    {
                        sample = ScaleByteToShort(audioFile.GetNextSample_8bit());
                        if (sample > highestSample)
                            highestSample = sample;
                    }
                }
                else if (audioFile.BitsPerSample == 16)
                {
                    short sample = 0;
                    for (int i = 0; i < audioFile.NumSamples; ++i)
                    {
                        sample = audioFile.GetNextSample_16bit();
                        if (sample > highestSample)
                            highestSample = sample;
                    }
                }

                audioFile.Close();
            }
        }
        catch
        {
            // log exception
        }

        return highestSample;
    }
Exemple #20
0
    /// <summary>
    /// Returns the highest number of channels in a set of audio files.
    /// </summary>
    /// <param name="pFilenames">An array containing the audio file names</param>
    /// <returns>The highest number of channels in the set of audio files</returns>
    public static byte HighestNumChannels(String[] pFilenames)
    {
        byte numChannels = 0;

        if (pFilenames != null)
        {
            WAVFile audioFile = new WAVFile();
            String retval = "";
            foreach (String filename in pFilenames)
            {
                try
                {
                    retval = audioFile.Open(filename, WAVFileMode.READ);
                    if (retval.Length == 0)
                    {
                        if (audioFile.NumChannels > numChannels)
                            numChannels = audioFile.NumChannels;
                        audioFile.Close();
                    }
                }
                catch
                {
                    // log exception
                }
            }
        }

        return numChannels;
    }
Exemple #21
0
    /// <summary>
    /// Adjusts the volume level of a WAV file, saving the adjusted file as a separate file.
    /// </summary>
    /// <param name="pSrcFilename">The name of the WAV file to adjust</param>
    /// <param name="pDestFilename">The name to use for the volume-adjusted WAV file</param>
    /// <param name="pMultiplier">The value by which to multiply the audio samples</param>
    public static void AdjustVolume_Copy(String pSrcFilename, String pDestFilename, double pMultiplier)
    {
        // If an empty source or destination file were passed in, then throw an exception.
        if (pSrcFilename.Length == 0)
            throw new WAVFileReadException("Blank filename specified.", "WAVFile.AdjustVolume_Copy()");
        if (pDestFilename.Length == 0)
            throw new WAVFileWriteException("Blank filename specified.", "WAVFile.AdjustVolume_Copy()");

        // Open the srouce file
        WAVFile srcFile = new WAVFile();
        String retval = srcFile.Open(pSrcFilename, WAVFileMode.READ);
        if (retval.Length == 0)
        {
            // Check to make sure the input file has a supported number of bits/sample and sample rate.  If
            // not, then throw an exception.
            if (!SupportedBitsPerSample(srcFile.BitsPerSample))
            {
                WAVFileBitsPerSampleException ex = new WAVFileBitsPerSampleException(pSrcFilename +
                                                          " has unsupported bits/sample ("
                                                          + srcFile.BitsPerSample.ToString() + ")",
                                                          "WAVFile.AdjustVolume_Copy()", srcFile.BitsPerSample);
                srcFile.Close();
                throw ex;
            }

            // Open the destination file and start copying the adjusted audio data to it.
            WAVFile destFile = new WAVFile();
            destFile.Create(pDestFilename, srcFile.IsStereo, srcFile.SampleRateHz, srcFile.BitsPerSample);
            if (srcFile.BitsPerSample == 8)
            {
                byte sample = 0;
                for (int i = 0; i < srcFile.NumSamples; ++i)
                {
                    // Note: Only multiply the sample if pMultiplier is not 1.0 (if the multiplier is
                    // 1.0, then it would be good to avoid any binary roundoff error).
                    sample = srcFile.GetNextSample_8bit();
                    if (pMultiplier != 1.0)
                        sample = (byte)((double)sample * pMultiplier);
                    destFile.AddSample_8bit(sample);
                }
            }
            else if (srcFile.BitsPerSample == 16)
            {
                short sample = 0;
                for (int i = 0; i < srcFile.NumSamples; ++i)
                {
                    // Note: Only multiply the sample if pMultiplier is not 1.0 (if the multiplier is
                    // 1.0, then it would be good to avoid any binary roundoff error).
                    sample = srcFile.GetNextSample_16bit();
                    if (pMultiplier != 1.0)
                        sample = (short)((double)sample * pMultiplier);
                    destFile.AddSample_16bit(sample);
                }
            }

            srcFile.Close();
            destFile.Close();
        }
        else
            throw new WAVFileReadException(retval, "WAVFile.AdjustVolume_Copy()");
    }
Exemple #22
0
        private void frmReplace_Load(object sender, EventArgs e)
        {
            labelSampleSize.Text          = (sampleSize / 1024).ToString() + " KB";
            labelSampleDuration.Text      = Utils.getDurationString(sampleSamples16Bit, sampleSampleRate);
            labelSampleSampleRate.Text    = sampleSampleRate.ToString() + " Hz";
            labelSampleBitsPerSecond.Text = sampleBitsPerSecond.ToString();
            labelSampleChannels.Text      = sampleChannels.ToString();

            WAVFile wav = new WAVFile();

            wav.Open(WAVPath, WAVFile.WAVFileMode.READ);
            labelFileSize.Text          = (wav.DataSizeBytes / 1024).ToString() + " KB";
            labelFileDuration.Text      = Utils.getDurationString(wav.NumSamples, wav.SampleRateHz);
            labelFileSampleRate.Text    = wav.SampleRateHz.ToString() + " Hz";
            labelFileBitsPerSecond.Text = wav.BitsPerSample.ToString();
            labelFileChannels.Text      = wav.NumChannels.ToString();
            labelFileCodecID.Text       = wav.EncodingType.ToString();
            wav.Close();

            if (labelFileCodecID.Text != "1")
            {
                labelAdvice.Text           = "ERROR! The file you've chosen is not Uncompressed PCM encoded and thus cannot be used as replacement.";
                labelFileCodecID.ForeColor = Color.DarkRed;
                buttonReplace.Enabled      = false;
                return;
            }
            else
            {
                labelFileCodecID.ForeColor = Color.Green;
            }

            if (labelFileBitsPerSecond.Text != "16")
            {
                labelAdvice.Text = "ERROR! The file you've chosen does not have 16 bits per second and thus cannot be used as replacement.";
                labelFileBitsPerSecond.ForeColor   = Color.DarkRed;
                labelSampleBitsPerSecond.ForeColor = Color.DarkRed;
                buttonReplace.Enabled = false;
                return;
            }
            else
            {
                labelSampleBitsPerSecond.ForeColor = Color.Green; labelFileBitsPerSecond.ForeColor = Color.Green;
            }

            if (labelFileChannels.Text != labelSampleChannels.Text)
            {
                labelAdvice.Text              = "ERROR! The file you've chosen does not have the same amount of channels as the original sample and thus cannot be used as replacement.";
                labelFileChannels.ForeColor   = Color.DarkRed;
                labelSampleChannels.ForeColor = Color.DarkRed;
                buttonReplace.Enabled         = false;
                return;
            }
            else
            {
                labelSampleChannels.ForeColor = Color.Green; labelFileChannels.ForeColor = Color.Green;
            }

            if (labelFileDuration.Text != labelSampleDuration.Text)
            {
                labelFileDuration.ForeColor   = Color.DarkGoldenrod;
                labelSampleDuration.ForeColor = Color.DarkGoldenrod;
                labelAdvice.ForeColor         = Color.DarkGoldenrod;
                labelAdvice.Text = "WARNING! The file you've chosen does not have the same duration as the original sample. It is recommended to use a file with somewhat the same duration.";
            }
            else
            {
                labelSampleDuration.ForeColor = Color.Green; labelFileDuration.ForeColor = Color.Green;
            }

            if (labelFileSampleRate.Text != labelSampleSampleRate.Text)
            {
                labelFileSampleRate.ForeColor   = Color.DarkGoldenrod;
                labelSampleSampleRate.ForeColor = Color.DarkGoldenrod;
                labelAdvice.ForeColor           = Color.DarkGoldenrod;
                labelAdvice.Text = "WARNING! The file you've chosen does not have the same sample rate as the original sample. It is highly recommended to use a file with the same sample rate.";
            }
            else
            {
                labelSampleSampleRate.ForeColor = Color.Green; labelFileSampleRate.ForeColor = Color.Green;
            }

            labelSampleSize.ForeColor = Color.Green;
            labelFileSize.ForeColor   = Color.Green;
            buttonReplace.Enabled     = true;

            if (labelAdvice.Text != "Please wait...")
            {
                return;
            }
            labelAdvice.ForeColor = Color.Green;
            labelAdvice.Text      = "This file looks okay as replacement. Click Replace to replace the original sample with it.";
        }
Exemple #23
0
    /// <summary>
    /// For 8-bit WAV files: Adjusts the volume level and converts it to a 16-bit audio file.
    /// The converted data is saved to a separate file.
    /// </summary>
    /// <param name="pSrcFilename">The name of the WAV file to convert</param>
    /// <param name="pDestFilename">The name to use for the converted WAV file</param>
    /// <param name="pMultiplier">The volume multiplier</param>
    public static void AdjustVolume_Copy_8BitTo16Bit(String pSrcFilename, String pDestFilename, double pMultiplier)
    {
        // If an empty source or destination file were passed in, then throw an exception.
        if (pSrcFilename.Length == 0)
            throw new WAVFileReadException("Blank filename specified.", "WAVFile.AdjustVolume_Copy_8BitTo16Bit()");
        if (pDestFilename.Length == 0)
            throw new WAVFileWriteException("Blank filename specified.", "WAVFile.AdjustVolume_Copy_8BitTo16Bit()");

        // Open the srouce file
        WAVFile srcFile = new WAVFile();
        String retval = srcFile.Open(pSrcFilename, WAVFileMode.READ);
        if (retval.Length == 0)
        {
            // Check to make sure the input file has 8 bits per sample.  If not, then throw an exception.
            if (srcFile.BitsPerSample != 8)
            {
                WAVFileBitsPerSampleException ex = new WAVFileBitsPerSampleException(pSrcFilename +
                                                          ": 8 bits per sample required, and the file has " +
                                                          srcFile.BitsPerSample.ToString() + " bits per sample.",
                                                          "WAVFile.AdjustVolume_Copy_8BitTo16Bit()",
                                                          srcFile.BitsPerSample);
                srcFile.Close();
                throw ex;
            }

            // Open the destination file
            WAVFile destFile = new WAVFile();
            destFile.Create(pDestFilename, srcFile.IsStereo, srcFile.SampleRateHz, 16, true);

            // Copy the data
            short sample_16bit = 0;
            while (srcFile.NumSamplesRemaining > 0)
            {
                // Scale the sample from 8-bit to 16 bits
                sample_16bit = ScaleByteToShort(srcFile.GetNextSample_8bit());

                // Now, apply pMultiplier if it is not 1.0
                if (pMultiplier != 1.0)
                    sample_16bit = (short)((double)sample_16bit * pMultiplier);

                // Save the sample to the destination file
                destFile.AddSample_16bit(sample_16bit);
            }

            srcFile.Close();
            destFile.Close();
        }
        else
            throw new WAVFileReadException(retval, "WAVFile.AdjustVolume_Copy_8BitTo16Bit()");
    }
Exemple #24
0
    /// <summary>
    /// Converts a WAV file's bits/sample and number of channels to a separate WAV file.
    /// </summary>
    /// <param name="pSrcFilename">The name of the file to convert</param>
    /// <param name="pDestFilename">The destination file name</param>
    /// <param name="pBitsPerSample">The destination's number of bits/sample</param>
    /// <param name="pStereo">Whether or not the destination should be stereo</param>
    /// <param name="pVolumeMultiplier">A multiplier that can be used to adjust the volume of the output audio file</param>
    public static void CopyAndConvert(String pSrcFilename, String pDestFilename, short pBitsPerSample, bool pStereo, double pVolumeMultiplier)
    {
        WAVFile srcFile = new WAVFile();
        String retval = srcFile.Open(pSrcFilename, WAVFileMode.READ);
        if (retval.Length > 0)
            throw new WAVFileException(retval, "WAVFile.Convert_Copy()");

        WAVFile destFile = new WAVFile();
        destFile.Create(pDestFilename, pStereo, srcFile.SampleRateHz, pBitsPerSample);
        if ((srcFile.BitsPerSample == 8) && (pBitsPerSample == 8))
        {
            byte sample = 0;
            if (srcFile.IsStereo && !pStereo)
            {
                // 8-bit to 8-bit, stereo to mono: Average each 2 samples
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = (byte)((short)((short)srcFile.GetNextSample_8bit() + (short)srcFile.GetNextSample_8bit()) / 2);
                    if (pVolumeMultiplier != 1.0)
                        sample = (byte)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_8bit(sample);
                }
            }
            else if ((srcFile.IsStereo && pStereo) || (!srcFile.IsStereo && !pStereo))
            {
                // 8-bit to 8-bit, stereo to stereo or mono to mono
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSample_8bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (byte)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_8bit(sample);
                }
            }
            else if (!srcFile.IsStereo && pStereo)
            {
                // 8-bit to 8-bit, mono to stereo: Write each sample twice
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSample_8bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (byte)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_8bit(sample);
                    destFile.AddSample_8bit(sample);
                }
            }
        }
        else if ((srcFile.BitsPerSample == 8) && (pBitsPerSample == 16))
        {
            short sample = 0;
            if (srcFile.IsStereo && !pStereo)
            {
                // 8-bit to 16 bit, stereo to mono: Average each 2 samples
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = (short)((int)((int)srcFile.GetNextSampleAs16Bit() + (int)srcFile.GetNextSampleAs16Bit()) / 2);
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                }
            }
            else if ((srcFile.IsStereo && pStereo) || (!srcFile.IsStereo && !pStereo))
            {
                // 8-bit to 16 bit, stereo to stereo or mono to mono
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSampleAs16Bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                }
            }
            else if (!srcFile.IsStereo && pStereo)
            {
                // 8-bit to 16 bit, mono to stereo: Write each sample twice
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSampleAs16Bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                    destFile.AddSample_16bit(sample);
                }
            }
        }
        else if ((srcFile.BitsPerSample == 16) && (pBitsPerSample == 8))
        {
            byte sample = 0;
            if (srcFile.IsStereo && !pStereo)
            {
                // 16-bit to 8-bit, stereo to mono: Average each 2 samples
                short sample_16bit = 0;
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample_16bit = (short)((int)srcFile.GetNextSample_16bit() + (int)srcFile.GetNextSample_16bit() / 2);
                    if (pVolumeMultiplier != 1.0)
                        sample_16bit = (short)((double)sample_16bit * pVolumeMultiplier);
                    sample = ScaleShortToByte(sample_16bit);
                    destFile.AddSample_8bit(sample);
                }
            }
            else if ((srcFile.IsStereo && pStereo) || (!srcFile.IsStereo && !pStereo))
            {
                // 16-bit to 8-bit, stereo to stereo or mono to mono
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = ScaleShortToByte(srcFile.GetNextSample_16bit());
                    if (pVolumeMultiplier != 1.0)
                        sample = (byte)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_8bit(sample);
                }
            }
            else if (!srcFile.IsStereo && pStereo)
            {
                // 16-bit to 8-bit, mono to stereo: Write each sample twice
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = ScaleShortToByte(srcFile.GetNextSample_16bit());
                    if (pVolumeMultiplier != 1.0)
                        sample = (byte)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_8bit(sample);
                    destFile.AddSample_8bit(sample);
                }
            }
        }
        else if ((srcFile.BitsPerSample == 16) && (pBitsPerSample == 16))
        {
            short sample = 0;
            if (srcFile.IsStereo && !pStereo)
            {
                // 16-bit to 16-bit, stereo to mono: Average each 2 samples
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = (short)((int)((int)srcFile.GetNextSample_16bit() + (int)srcFile.GetNextSample_16bit()) / 2);
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                }
            }
            else if ((srcFile.IsStereo && pStereo) || (!srcFile.IsStereo && !pStereo))
            {
                // 16-bit to 16-bit, stereo to stereo or mono to mono
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSample_16bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                }
            }
            else if (!srcFile.IsStereo && pStereo)
            {
                // 16-bit to 16-bit, mono to stereo: Write each sample twice
                while (srcFile.NumSamplesRemaining > 0)
                {
                    sample = srcFile.GetNextSample_16bit();
                    if (pVolumeMultiplier != 1.0)
                        sample = (short)((double)sample * pVolumeMultiplier);
                    destFile.AddSample_16bit(sample);
                    destFile.AddSample_16bit(sample);
                }
            }
        }

        destFile.Close();
        srcFile.Close();
    }
Exemple #25
0
    /// <summary>
    /// Returns a WAVFormat struct containing audio format information
    /// (# channels, sample rate, and bits per sample) for a WAV file.
    /// </summary>
    /// <param name="pFilename">The name of the file about which to retrieve format information</param>
    /// <returns>A WAVFormat struct object containing the audio format information for the open file</returns>
    public static WAVFormat GetAudioFormat(String pFilename)
    {
        WAVFormat format = new WAVFormat();

        WAVFile audioFile = new WAVFile();
        if (audioFile.Open(pFilename, WAVFileMode.READ).Length == 0)
        {
            format.BitsPerSample = audioFile.mBitsPerSample;
            format.NumChannels = audioFile.mNumChannels;
            format.SampleRateHz = audioFile.mSampleRateHz;

            audioFile.Close();
        }

        return (format);
    }
Exemple #26
0
    /// <summary>
    /// Returns the highest number of bits per sample in a set of audio files.
    /// </summary>
    /// <param name="pFilenames">An array containing the audio file names</param>
    /// <returns>The highest number of bits per sample in the set of audio files</returns>
    public static short HighestBitsPerSample(String[] pFilenames)
    {
        short bitsPerSample = 0;

        if (pFilenames != null)
        {
            WAVFile audioFile = new WAVFile();
            String retval = "";
            foreach (String filename in pFilenames)
            {
                try
                {
                    retval = audioFile.Open(filename, WAVFileMode.READ);
                    if (retval.Length == 0)
                    {
                        if (audioFile.BitsPerSample > bitsPerSample)
                            bitsPerSample = audioFile.BitsPerSample;
                        audioFile.Close();
                    }
                }
                catch
                {
                    // log exception
                }
            }
        }

        return bitsPerSample;
    }
        // STAThread is ESSENTIAL to make this work
		[STAThread] public static void Main(string[] args)
		{
            // no messing, this is high priority stuff
			Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Process myP = Process.GetCurrentProcess();
            myP.ProcessorAffinity = (IntPtr)1;
            
			// make sure we have at least one ASIO driver installed
			if (AsioDriver.InstalledDrivers.Length == 0)
			{
				Console.WriteLine("There appears to be no ASIO drivers installed on your system.");
				Console.WriteLine("If your soundcard supports ASIO natively, install the driver");
				Console.WriteLine("from the support disc. If your soundcard has no native ASIO support");
				Console.WriteLine("you can probably use the generic ASIO4ALL driver.");
				Console.WriteLine("You can download this from: http://www.asio4all.com/");
				Console.WriteLine("It's very good!");
				Console.WriteLine();
				Console.WriteLine("Hit Enter to exit...");
				Console.ReadLine();
				return;
			}

            // bingo, we've got at least one
			Console.WriteLine("Your system has the following ASIO drivers installed:");
			Console.WriteLine();

            // so iterate through them
			for (int index = 0; index < AsioDriver.InstalledDrivers.Length; index++)
			{
                // and display them
				Console.WriteLine(string.Format("  {0}. {1}", index + 1, AsioDriver.InstalledDrivers[index]));
			}

			Console.WriteLine();

			int driverNumber = 0;

            // get them to choose one
			while (driverNumber < 1 || driverNumber > AsioDriver.InstalledDrivers.Length)
			{
				// we'll keep telling them this until they make a valid selection
				Console.Write("Select which driver you wish to use (x for exit): ");
				ConsoleKeyInfo key = Console.ReadKey();
				Console.WriteLine();

				// deal with exit condition
				if (key.KeyChar == 'x') return;

				// convert from ASCII to int
				driverNumber = key.KeyChar - 48;
			}

			Console.WriteLine();
			Console.WriteLine("Using: " + AsioDriver.InstalledDrivers[driverNumber - 1]);
			Console.WriteLine();

			// load and activate the desited driver
			AsioDriver driver = AsioDriver.SelectDriver(AsioDriver.InstalledDrivers[driverNumber - 1]);

			// popup the driver's control panel for configuration
            driver.ShowControlPanel();

			// now dump some details
            Console.WriteLine("  Driver name = " + driver.DriverName);
            Console.WriteLine("  Driver version = " + driver.Version);
            Console.WriteLine("  Input channels = " + driver.NumberInputChannels);
            Console.WriteLine("  Output channels = " + driver.NumberOutputChannels);
            Console.WriteLine("  Min buffer size = " + driver.BufferSizex.MinSize);
            Console.WriteLine("  Max buffer size = " + driver.BufferSizex.MaxSize);
            Console.WriteLine("  Preferred buffer size = " + driver.BufferSizex.PreferredSize);
            Console.WriteLine("  Granularity = " + driver.BufferSizex.Granularity);
            Console.WriteLine("  Sample rate = " + driver.SampleRate);

			// get our driver wrapper to create its buffers
			driver.CreateBuffers(false);

			// write out the input channels
            Console.WriteLine("  Input channels found = " + driver.InputChannels.Length);
			Console.WriteLine("  ----");

            foreach (Channel channel in driver.InputChannels)
			{
				Console.WriteLine(channel.Name);
			}

			// and the output channels
            Console.WriteLine("  Output channels found = " + driver.OutputChannels.Length);
            Console.WriteLine("----");

            foreach (Channel channel in driver.OutputChannels)
			{
				Console.WriteLine(channel.Name);
			}

            Console.Write("Select which effect you wish to use (1 = delay, 2 = flanger, 3 = phaser, 4 = reverb): ");
            ConsoleKeyInfo useEffect = Console.ReadKey();
            if (useEffect.KeyChar == '1')
                effectType = effect.delay;
            else if (useEffect.KeyChar == '2')
                effectType = effect.flanger;
            else if (useEffect.KeyChar == '3')
                effectType = effect.phaser;
            else if (useEffect.KeyChar == '4')
                effectType = effect.reverb;
            else
                effectType = effect.none;



            // create standard sized buffers with a size of PreferredSize x MaxBuffers 
            _delayBuffer = new float[driver.BufferSizex.PreferredSize, MaxBuffers];

            // create a feedback buffer for the delay effect
            _delayFBbuffer = new float[driver.BufferSizex.PreferredSize, MaxBuffers];

            // create a input buffer for reverb effect
            _delayINbuffer = new float[driver.BufferSizex.PreferredSize, MaxBuffers];

            // create a output buffer for reverb effect
            _delayOUTbuffer = new float[driver.BufferSizex.PreferredSize, MaxBuffers];

            // this is our buffer fill event we need to respond to
            driver.BufferUpdate += new EventHandler(AsioDriver_BufferUpdate);

            // and off we go
            driver.Start();

            // create a wav file for recording
            wav.Create("test.wav", true, 44100, 16);

            // wait for enter key
            Console.WriteLine();
            Console.WriteLine("Press Enter to end");
			Console.ReadLine();

            // and all done
            driver.Stop();

            // close the wav file
            wav.Close();

        }
Exemple #28
0
        static void Main(string[] args)
        {
            //Debug test
            //args = (@"E:\Mijn documenten\Visual Studio 2010\ADPCMEncoder\~24000HZTEST.wav|test").Split(Convert.ToChar("|"));
            //args = (@"E:\Mijn documenten\Visual Studio 2010\ADPCMEncoder\TestFiles\LoadingSNOW.wav|test").Split(Convert.ToChar("|"));

            //Print header
            Console.WriteLine("=================");
            Console.WriteLine("IMA ADPCM Encoder");
            Console.WriteLine(" by Flitskikker");
            Console.WriteLine("=================");
            Console.WriteLine("");

            //Check args
            if (args.Length == 0)
            {
                //No args
                Console.WriteLine("ERROR: No command line arguments passed. Press any key to exit...");
                Console.ReadLine();
                Environment.Exit(1);
            }

            //Check file
            if (!File.Exists(args[0]))
            {
                //File not found
                Console.WriteLine("ERROR: File \"" + args[0] + "\" not found. Press any key to exit...");
                Console.ReadLine();
                Environment.Exit(2);
            }

            //Print file
            Console.WriteLine("File: " + args[0]);
            Console.WriteLine("");

            //Load file
            WAVFile wav = new WAVFile();

            wav.Open(args[0], WAVFile.WAVFileMode.READ);

            //Show WAV info
            Console.WriteLine("WAV Info:");
            Console.WriteLine("\tBits per sample:\t" + wav.BitsPerSample.ToString() + " bits");
            Console.WriteLine("\tBytes per sample:\t" + wav.BytesPerSample.ToString());
            Console.WriteLine("\tBytes per second:\t" + wav.BytesPerSec.ToString());
            Console.WriteLine("\tData size:\t\t" + wav.DataSizeBytes.ToString() + " bytes");
            Console.WriteLine("\tDuration:\t\t" + Math.Round(Convert.ToDecimal((double)wav.NumSamples / (double)wav.SampleRateHz), 2).ToString() + " seconds (" + Utils.getDurationString(wav.NumSamples, wav.SampleRateHz) + ")");
            Console.WriteLine("\tEncoding type:\t\t" + wav.EncodingType.ToString());
            Console.WriteLine("\tFile size:\t\t" + wav.FileSizeBytes.ToString() + " bytes");
            Console.WriteLine("\t# of channels:\t\t" + wav.NumChannels.ToString());
            Console.WriteLine("\t# of samples:\t\t" + wav.NumSamples.ToString());
            Console.WriteLine("\tRIFF type:\t\t" + wav.RIFFTypeString);
            Console.WriteLine("\tSample Rate:\t\t" + wav.SampleRateHz.ToString() + " Hz");
            Console.WriteLine("\tWAV header:\t\t" + wav.WAVHeaderString);
            Console.WriteLine("");

            //Check bits
            if (wav.BitsPerSample != 16)
            {
                //Not 16 bits
                Console.WriteLine("ERROR: WAV should have 16 bits per sample. Press any key to exit...");
                Console.ReadLine();
                Environment.Exit(1);
            }

            //Check bytes per sample
            if (wav.BytesPerSample / wav.NumChannels != 2)
            {
                //Not 2 bytes
                Console.WriteLine("ERROR: WAV should have (wav.NumChannels * 2) bytes per sample. Press any key to exit...");
                Console.ReadLine();
                Environment.Exit(1);
            }

            //Print message
            Console.WriteLine("Ready to go! Press any key when ready...");

            //Wait for input
            Console.ReadLine();

            if (wav.NumChannels > 1)
            {
                //Split channels
                Console.WriteLine("");
                Console.WriteLine("Saving separate channels...");
                Console.WriteLine("");

                List <WAVFile> wavs = new List <WAVFile>();

                for (int c = 0; c < wav.NumChannels; c++)
                {
                    wavs.Add(new WAVFile());
                    wavs[c].Create(Path.GetDirectoryName(args[0]) + "\\" + Path.GetFileNameWithoutExtension(args[0]) + "_" + (c + 1).ToString() + ".wav", false, wav.SampleRateHz, wav.BitsPerSample, true);
                }

                int numSamplesCorrected = ((wav.DataSizeBytes - 8) / wav.BytesPerSample);

                //for (long i = 0; i < wav.NumSamples / wav.NumChannels; i++) {
                for (long i = 0; i < numSamplesCorrected; i++)
                {
                    for (int c = 0; c < wav.NumChannels; c++)
                    {
                        wavs[c].AddSample_16bit(wav.GetNextSampleAs16Bit());
                    }
                }

                for (int c = 0; c < wav.NumChannels; c++)
                {
                    wavs[c].Close();
                }
            }

            //Encode
            Console.WriteLine("");
            Console.WriteLine("Encoding file(s)...");
            Console.WriteLine("");

            IMAADPCM.ADPCMState state = new IMAADPCM.ADPCMState();
            WAVFile             cwav  = new WAVFile();
            int nc = wav.NumChannels;

            for (int c = 0; c < wav.NumChannels; c++)
            {
                Console.WriteLine("Encoding file: " + Path.GetDirectoryName(args[0]) + "\\" + Path.GetFileNameWithoutExtension(args[0]) + "_" + (c + 1).ToString() + ".bin");

                MemoryStream ms = new MemoryStream();
                cwav = new WAVFile();

                // Open splitted WAV
                if (wav.NumChannels > 1)
                {
                    cwav.Open(Path.GetDirectoryName(args[0]) + "\\" + Path.GetFileNameWithoutExtension(args[0]) + "_" + (c + 1).ToString() + ".wav", WAVFile.WAVFileMode.READ_WRITE);
                }
                else
                {
                    cwav = wav;
                    //wav.Close();
                    //cwav.Open(args[0], WAVFile.WAVFileMode.READ_WRITE);
                }

                byte[] bytes     = new byte[2];
                int    loopValue = ((cwav.DataSizeBytes - 8) / cwav.BytesPerSample);

                //Actual encode
                for (long i = 0; i < loopValue / 2; i++)
                {
                    bytes[0] = IMAADPCM.encodeADPCM(cwav.GetNextSampleAs16Bit(), ref state);
                    bytes[1] = IMAADPCM.encodeADPCM(cwav.GetNextSampleAs16Bit(), ref state);
                    ms.Write(BitConverter.GetBytes(Convert.ToInt32(Utils.binaryString(bytes[1], 4) + Utils.binaryString(bytes[0], 4), 2)), 0, 1);
                }

                //Get WAV data
                byte[] dataWAV = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(dataWAV, 0, (int)ms.Length);
                ms.Close();

                //Create file
                FileStream fs = new FileStream(Path.GetDirectoryName(args[0]) + "\\" + Path.GetFileNameWithoutExtension(args[0]) + "_" + (c + 1).ToString() + ".bin", FileMode.Create, FileAccess.ReadWrite);

                //Write sample
                fs.Seek(0, SeekOrigin.Begin);
                fs.Write(dataWAV, 0, dataWAV.Length);

                //Close
                cwav.Close();
                ms.Close();
                fs.Close();

                if (nc == 1)
                {
                    break;
                }
            }

            //Close WAV file
            wav.Close();

            //Print message
            Console.WriteLine("");
            Console.WriteLine("Done! Press any key to exit...");

            //Wait for input
            Console.ReadLine();

            //Exit
            Environment.Exit(0);
        }