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 WAVCreator(short formatAudio, short channels, int frequency, short bitspersample, uint time, int formWAV, string path)
 {
     Header = CreateHeader(formatAudio, channels, frequency, bitspersample);
     Form   = (FormWAV)formWAV;
     CreateSamples(time);
     WAVFile.WriteFile(path, Header, Buffer);
 }
Exemple #3
0
        public void TestProcess()
        {
            Porcupine p = new Porcupine(Path.Combine(Environment.CurrentDirectory, "porcupine_params.pv"), keywordFilePath: $"{GetAbsRootPath()}resources/keyword_files/porcupine_{GetEnvironmentName()}.ppn", sensitivity: 0.5f);

            Assert.AreEqual(PicoVoiceStatus.SUCCESS, p.Status, "the status of the creation of the recognition system has failed");
            WAVFile file = new WAVFile();

            file.Open("porcupine.wav", WAVFile.WAVFileMode.READ);
            Assert.AreEqual(p.SampleRate() / 1000, file.BitsPerSample, "The samplerate is not equal!!!");
            List <short> data = new List <short>();

            while (file.NumSamplesRemaining > 0)
            {
                data.Add(BitConverter.ToInt16(file.GetNextSample_ByteArray()));
            }

            int framecount = (int)Math.Floor((decimal)(data.Count / p.FrameLength()));
            var results    = new List <bool>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * p.FrameLength();
                int          count = p.FrameLength();
                List <short> frame = data.GetRange(start, count);
                p.Process(frame.ToArray(), out bool result);
                results.Add(result);
            }

            var res = results.Count(x => x);

            Assert.AreEqual(1, res, $"The result is not as expected, expected {1} got {res}");
            p.Dispose();
        }
Exemple #4
0
        private static FileInfo ConvertToWEM(FileInfo file)
        {
            DirectoryInfo dir;

            if (!Directory.Exists(@".\AUDIO_TEMP"))
            {
                dir            = Directory.CreateDirectory(@".\AUDIO_TEMP");
                dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }
            else
            {
                dir = new DirectoryInfo(@".\AUDIO_TEMP");
            }
            if (file.Extension.ToLower() == ".wav")
            {
                WAVFile wav = new WAVFile(file.FullName);
                WEMFile wem = wav.ConvertToWEM();

                string newWemPath = @".\AUDIO_TEMP\" + file.Name + ".wem";
                return(wem.SaveToFile(newWemPath));
            }
            else
            {
                // Guarantees the extension is wav.
                return(ConvertToWEM(FFmpegWrapper.ConvertToWaveFile(file.FullName, dir)));
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Drag n' drop a WEM or any audio file onto this EXE to convert it. WEM will be converted to WAV no matter what.");
                Console.WriteLine("Press any key to quit...");
                Console.ReadKey(true);
                return;
            }

            FileInfo file = new FileInfo(args[0]);

            if (file.Extension.ToLower() == ".wem")
            {
                Console.WriteLine("WARNING: WEM conversion is a bit busted right now! If your file is broken, sorry! A patch will be out ASAP.");
                WEMFile wem = new WEMFile(file.FullName);
                WAVFile wav = wem.ConvertToWAV();
                wav.SaveToFile(file.FullName + ".wav");
            }
            else
            {
                file = FFmpegWrapper.ConvertToWaveFile(file.FullName);
                WAVFile wav = new WAVFile(file.FullName);
                WEMFile wem = wav.ConvertToWEM();
                wem.SaveToFile(args[0] + ".wem");
            }
        }
Exemple #6
0
 public void TestGenerateTone()
 {
     double[] data;
     // 1000 samples, 1 Hz, 1 s, 1.0 amplitude
     WAVFile.generateTone(1000, 1.0, 1.0, 1.0, out data);
     Assert.AreEqual(1.0, data[0], 0.001, "Data generation failed at data[0].");
     Assert.AreEqual(-1.0, data[499], 0.001, "Data generation failed at data[499].");
 }
Exemple #7
0
 private static void WriteWAVFile(BlamSound blamSound)
 {
     using (EndianWriter output = new EndianWriter(new FileStream(WAVFile, FileMode.Create, FileAccess.Write, FileShare.None), EndianFormat.BigEndian))
     {
         WAVFile WAVfile = new WAVFile(blamSound);
         WAVfile.Write(output);
     }
 }
        void Instance_Updated()
        {
            double a      = (PBBRenderer.Instance.TotalFragmentsActions + 100);
            double b      = (PBBRenderer.Instance.FragmentActionsDone + WAVFile.GetAmountDone());
            double p      = 100 / a * b;
            string status = ((int)p).ToString() + "% - ";

            string time = (DateTime.Now - startTime).Hours.ToString("00") + ":" + (DateTime.Now - startTime).Minutes.ToString("00") + ":" + (DateTime.Now - startTime).Seconds.ToString("00");

            if (PBBRenderer.Instance.ActiveStatus == 0)
            {
                status += "MP3 bestanden voorbereiden. . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 1)
            {
                status += "Audio mixen . . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 2)
            {
                status += "Mix afronden . . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 3)
            {
                status += "Converteren naar MP3 . . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 4)
            {
                status += "MP3 knippen . . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 5)
            {
                status += "Opruimen . . .";
            }
            else if (PBBRenderer.Instance.ActiveStatus == 6)
            {
                status += "Klaar";
            }

            if (label1.InvokeRequired || progressBar1.InvokeRequired)
            {
                this.label3.BeginInvoke((MethodInvoker) delegate() { label3.Text = "Tijd gekost: " + time; });
                this.label2.BeginInvoke((MethodInvoker) delegate() { label2.Text = status; });
                this.label1.BeginInvoke((MethodInvoker) delegate() { label1.Text = (PBBRenderer.Instance.FragmentActionsDone + (int)WAVFile.GetAmountDone()) + "/" + (PBBRenderer.Instance.TotalFragmentsActions + 100); });
                this.progressBar1.BeginInvoke((MethodInvoker) delegate() { progressBar1.Maximum = PBBRenderer.Instance.TotalFragmentsActions + 100; });
                this.progressBar1.BeginInvoke((MethodInvoker) delegate() { progressBar1.Value = PBBRenderer.Instance.FragmentActionsDone + (int)WAVFile.GetAmountDone(); });
            }
            else
            {
                label3.Text          = "Tijd gekost: " + time;
                label2.Text          = status;
                label1.Text          = (PBBRenderer.Instance.FragmentActionsDone + (int)WAVFile.GetAmountDone()) + "/" + (PBBRenderer.Instance.TotalFragmentsActions + 100);
                progressBar1.Maximum = PBBRenderer.Instance.TotalFragmentsActions + 100;
                progressBar1.Value   = PBBRenderer.Instance.FragmentActionsDone + (int)WAVFile.GetAmountDone();
            }

            Application.DoEvents();
        }
Exemple #9
0
            public Sample(WAVFile wavFile, bool isPlaying, bool isLooped, bool autoRewind, float volume, float speed)
            {
                this.wavFile = wavFile;
                position     = 0;

                this.isPlaying  = isPlaying;
                this.isLooped   = isLooped;
                this.autoRewind = autoRewind;
                this.volume     = volume;
                this.speed      = speed;
            }
 public RecordChannel(int index, string rootDir)
 {
     this.Index   = index;
     this.RootDir = Path.Combine(rootDir, string.Format("Kenh {0}", this.Index.ToString()));
     if (!Directory.Exists(this.RootDir))
     {
         Directory.CreateDirectory(this.RootDir);
     }
     _waveFile = null;
     _buffer   = new Queue <byte>();
 }
 public void StartRecord(byte poId)
 {
     if (!IsRecording)
     {
         this.CurrentPOId = poId;
         _waveFile        = new WAVFile();
         _waveFile.Create(NewRecordFileName(), false, 8000, 8);
         //this.IsPaused = false;
         this.PausedTime = null;
     }
 }
Exemple #12
0
        /// <summary>
        /// creats a mixer samlple from the given column index
        /// </summary>
        /// <param name="column">column number</param>
        /// <param name="sonifiedWAV"></param>
        /// <param name="imArr">the array to create from it a wav file</param>
        private void createMixer(int column, WAVFile sonifiedWAV, float[,] imArr)
        {
            int arrNotesLength = imArr.GetLength(0);

            float[] paramArray = new float[_scanHeight];

            for (int i = 0; i < arrNotesLength; i++)
            {
                paramArray[i] = imArr[i, column];
            }
            generateColumn(paramArray, column, _myEyeMusic.model.ScanSpeed, sonifiedWAV);
        }
Exemple #13
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 #14
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();
        }
Exemple #15
0
        private void FilenameGrid_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            // transfer the filenames to a string array
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            // loop through the string array, adding each filename to the ListBox
            foreach (string filename in files)
            {
                // Make sure the file is a WAV audio file before adding it.
                if (WAVFile.IsWaveFile(filename))
                {
                    AddAudioFilename(filename);
                }
            }
        }
        /// <summary>
        /// This is the function that actually performs the audio merging and runs as in a separate thread.
        /// </summary>
        private void AudioMergeWorker()
        {
            mAppForm.UseWaitCursor = true;

            try
            {
                // Disable the audio merge GUI elements on the main GUI
                mAppForm.DisableAudioMergeGUIElements();
                // Merge the audio files.  When done, set the status text in the GUI to say "Done.".
                WAVFile.MergeAudioFiles(mAudioFilenames, mDestFilename, mTempDir);

                // Clean and remove the temporary directory
                String retval = UtilityFunctions.DeleteDir(mTempDir);
                if (retval != "")
                {
                    MessageBox.Show(mAppForm, "Error removing temporary directory:\n" + mTempDir + "\n" + retval, "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (WAVFileAudioMergeException exc)
            {
                MessageBox.Show(mAppForm, "Audio merge exception: " + exc.Message, "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            catch (WAVFileException exc)
            {
                MessageBox.Show(mAppForm, "WAV file exception: " + exc.Message, "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            catch (Exception exc)
            {
                MessageBox.Show(mAppForm, exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                mAppForm.SetStatusLabel1Text("Done.");

                // Re-enable the audio merge GUI elements on the main GUI
                mAppForm.EnableAudioMergeGUIElements();
            }
            catch (Exception exc)
            {
                MessageBox.Show(mAppForm, exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            mAppForm.UseWaitCursor = false;
        }
Exemple #17
0
        public void MultipleKeywords()
        {
            var modelFilePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "porcupine_params.pv"));

            Assert.IsTrue(File.Exists(modelFilePath), $"File.Exists(modelFilePath) --> {modelFilePath}");
            paths.ForEach(keywordFilePath => Assert.IsTrue(File.Exists(keywordFilePath), $"File.Exists(keywordFilePath) --> {keywordFilePath}"));

            Porcupine p = new Porcupine(modelFilePath, keywordFilePaths: paths, sensitivities: senses);

            Assert.AreEqual(PicoVoiceStatus.SUCCESS, p.Status, "the status of the creation of the recognition system has failed");
            WAVFile file = new WAVFile();

            file.Open("multiple_keywords.wav", WAVFile.WAVFileMode.READ);
            Assert.AreEqual(p.SampleRate(), file.AudioFormat.SampleRateHz, "The samplerate is not equal!!!");
            List <short> data = new List <short>();

            while (file.NumSamplesRemaining > 0)
            {
                data.Add(BitConverter.ToInt16(file.GetNextSample_ByteArray()));
            }
            int framecount = (int)Math.Floor((decimal)(data.Count / p.FrameLength()));
            var results    = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int             start  = i * p.FrameLength();
                int             count  = p.FrameLength();
                List <short>    frame  = data.GetRange(start, count);
                PicoVoiceStatus status = p.ProcessMultipleKeywords(frame.ToArray(), out int result);
                if (result >= 0)
                {
                    results.Add(result);
                }
                Assert.AreEqual(PicoVoiceStatus.SUCCESS, status, "The status is not as expected");
            }

            var requiredRes = new[] { 8, 0, 1, 2, 3, 4, 5, 7, 8, 9 };

            Assert.AreEqual(requiredRes.Length, results.Count, $"expected results length are different expected {requiredRes.Length} got {results.Count}");
            for (var i = 0; i < results.Count; i++)
            {
                Assert.AreEqual(requiredRes[i], results[i], $"The result is not as expected, expected {requiredRes[i]} got {results[i]}");
            }

            p.Dispose();
        }
        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 #19
0
        private void MixWAVFiles()
        {
            this.CreateDirectoryIfNotExists(workingDir + "\\export\\total");

            while (true)
            {
                // Check if all threads need to be stopped
                if (StopCurrentThread())
                {
                    return;
                }

                if (fadeInOutWAV.Count == this.totalFragments && totalFragments > 0)
                {
                    break;
                }

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

            ActiveStatus = 1;

            List <WAVInputFile> files = new List <WAVInputFile>();

            for (int i = 0; i < fadeInOutWAV.Count; i++)
            {
                files.Add(new WAVInputFile(this.fadeInOutWAV[i], (fragmenten[i].FadeOut - new DateTime(2000, 1, 1)).TotalSeconds));
            }

            OnUpdated();

            try
            {
                WAVFile.MixAudioFiles(files.ToArray(), workingDir + "\\export\\total\\output.wav", workingDir + "\\export\\total\\temp");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }

            ActiveStatus = 3;
            OnUpdated();
        }
Exemple #20
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 #21
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 #22
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 #23
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 #24
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 #25
0
        private void LoadTapeSide(TapeSide tapeSide)
        {
            string path = Path.Combine(tapeManager.TapesDirectory, tapeSide.FilePath);

            if (music != null && loadedTapeSide != null)
            {
                loadedTapeSide.Position = music.GetCurrentPositionSeconds();
            }

            mixer.RemoveSample(music);
            music?.wavFile.Close();

            WAVFile wav = new WAVFile(); //default value in case of error

            try
            {
                wav = WAVFile.Load(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error while loading tape", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            music = new SoundMixer.Sample(wav, false, false, false, 0.2f, 1.0f);
            mixer.AddSample(music);
            mixer.SetRecordingSample(music);

            loadedTapeSide = tapeSide;
            music.SetCurrentPositionSeconds(tapeSide.Position);

            State = PlayerState.STOPPED;
            cassetteControl.LoadedTapeSide = tapeSide;
            cassetteButtons.Enabled        = true;

            counter.IgnoreNextSetPosition();

            cassetteClose.UpdatePlayback(true);
        }
Exemple #26
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 #27
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 #28
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];
        }
        /// <summary>
        /// Add a filename to our list of files for processing
        /// </summary>
        /// <param name="filename">The completely pathed filename of the file to read</param>
        private void AddAudioFilename(String filename)
        {
            WAVFormat format = WAVFile.GetAudioFormat(filename);

            if (format.NumChannels > 1)
            {
                //TODO: Pop up something here
                return;
            }

            if (format.BitsPerSample != 8 && format.BitsPerSample != 16)
            {
                Console.Out.WriteLine(format.BitsPerSample);
                return;
            }

            if (!WAVFile.IsWaveFile(filename))
            {
                //TODO: Pop up a window to alert the user that an invalid file was specified
                return;
            }

            Downsampler.WavetableRef wavref = new WavetableRef();
            wavref.filename = Path.GetFileName(filename);
            wavref.filedir  = Path.GetDirectoryName(filename);
            wavref.filepath = filename;
            mSoundFiles.Add(wavref);

            fileGridView.Rows.Add(1);

            int rowNum = fileGridView.Rows.Count - 1;

            fileGridView.Columns[0].AutoSizeMode     = DataGridViewAutoSizeColumnMode.Fill;
            fileGridView.Rows[rowNum].Cells[0].Value = wavref.filename;
            fileGridView.Rows[rowNum].Cells[1].Value = "Copy (As Array)";
            fileGridView.Rows[rowNum].Cells[2].Value = "Remove";
        }
Exemple #30
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 #31
0
    /// <summary>
    /// Returns whether or not the WAV file format (mono/stereo,
    /// sample rate, and bits per sampe) match another WAV file's
    /// format.
    /// </summary>
    /// <param name="pWAVFile">Another WAVFile object to compare with</param>
    /// <returns></returns>
    public bool FormatMatches(WAVFile pWAVFile)
    {
        bool retval = false;

        if (pWAVFile != null)
            retval = ((mNumChannels == pWAVFile.mNumChannels) &&
                      (mSampleRateHz == pWAVFile.mSampleRateHz) &&
                      (mBitsPerSample == pWAVFile.mBitsPerSample));

        return retval;
    }
Exemple #32
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 #33
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 #34
0
    /// <summary>
    /// Returns whether or not any audio samples are remaining to be read from an array of WAV files.
    /// </summary>
    /// <param name="WAVFileArray">An array of WAVFile objects that are currently open</param>
    /// <returns>true if there are samples that can still be read from any of the files, or false if not.</returns>
    private static bool SamplesRemain(WAVFile[] WAVFileArray)
    {
        bool samplesRemain = false;

        if (WAVFileArray != null)
        {
            for (int i = 0; i < WAVFileArray.GetLength(0); ++i)
            {
                if (WAVFileArray[i].NumSamplesRemaining > 0)
                {
                    samplesRemain = true;
                    break;
                }
            }
        }

        return (samplesRemain);
    }
Exemple #35
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 #36
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()");
    }
 protected override void CreateProjectRecording()
 {
     wavCreator = new WAVFile();
     tdmsFile = new TdmsFile(recordFileName, new TdmsFileOptions());
 }
Exemple #38
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 #39
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 #40
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;
    }
Exemple #41
0
 //Temporary function
 private void barButtonItem37_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     WAVFile wavFile = new WAVFile();
     wavFile.Open(@"C:\Users\faris\Documents\Sigsence DeskApp V.1.0\Projects\sigsenceProject\Audio\Record_13-10-2012_18-19-46.wav", WAVFile.WAVFileMode.READ);
     //wavFile.Open(@"C:\Users\faris\Documents\Sigsence DeskApp V.1.0\Projects\sigsenceProject\Audio\doh.wav", WAVFile.WAVFileMode.READ);
 }
Exemple #42
0
    // Returns left and right double arrays. 'right' will be null if sound is mono.
    public static WAVFile OpenWAV(byte[] wav)
    {
        if (!Encoding.ASCII.GetString(wav, 0, 4).Equals("RIFF"))
        {
            throw new System.Exception("Invalid WAV file");
        }

        WAVFile file = new WAVFile();

        file.sampleRate = System.BitConverter.ToInt32(wav, 24);

        // Determine if mono or stereo
        int channels = file.channels = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

        // Get past all the other sub chunks to get to the data subchunk:
        int pos = 12;   // First Subchunk ID from 12 to 16

        // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
        while (!(wav[pos] == 100 && wav[pos + 1] == 97 && wav[pos + 2] == 116 && wav[pos + 3] == 97))
        {
            pos += 4;
            int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
            pos += 4 + chunkSize;
        }
        pos += 8;

        // Pos is now positioned to start of actual sound data.
        //int samples = (wav.Length - pos) / 2;     // 2 bytes per sample (16 bit sound mono)
        //if(channels == 2)
        //    samples /= 2;        // 4 bytes per sample (16 bit stereo)

        int bytesPerSample = System.BitConverter.ToInt16(wav, 34) / 8;
        int samples        = (wav.Length - pos) / Mathf.Max(bytesPerSample * channels, 1);

        file.samples = samples;

        // Allocate memory (right will be null if only mono sound)
        float[] left = file.leftChannel = new float[samples];
        float[] right;
        if (channels == 2)
        {
            right = file.rightChannel = new float[samples];
        }
        else
        {
            right = file.rightChannel = null;
        }

        // Write to double array/s:
        int i = 0;

        while (pos < wav.Length)
        {
            if (bytesPerSample > 1)
            {
                left[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                pos    += 2;
                if (channels == 2)
                {
                    right[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                    pos     += 2;
                }
            }
            else    //8bits per sample
            {
                left[i] = (wav[pos] / 255f) * 2 - 1f;

                pos += 1;
                if (channels == 2)
                {
                    right[i] = (wav[pos] / 255f) * 2 - 1f;
                    pos     += 1;
                }
            }

            int   byteRate      = System.BitConverter.ToInt32(wav, 28);
            float samplesToFade = Mathf.Clamp(byteRate * 0.25f, 1, samples); //fade for 0.25s
            //fade to avoid audio popping on loops
            if (i >= samples - samplesToFade)
            {
                left[i] *= ((samples - i) / samplesToFade);
            }
            if (i <= samplesToFade)
            {
                left[i] *= i / samplesToFade;
            }

            i++;
        }

        return(file);
    }
Exemple #43
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 #44
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 #45
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;
    }