Пример #1
0
        private void ChangeVolume(object sender, EventArgs e)
        {
            if (this.listViewSongs.SelectedItems.Count > 0)
            {
                if (this.listViewSongs.SelectedItems[0].Group != this.listViewSongs.Groups["customMusic"])
                {
                    using (VolumeMessageBox messageBox = new VolumeMessageBox(this.lastVolume)) {
                        if (messageBox.ShowDialog(this) == DialogResult.OK)
                        {
                            this.lastVolume = messageBox.NewVolume;
                            SaveSettings(null, null);

                            if (this.listViewSongs.SelectedItems[0].ImageIndex == 1)
                            {
                                this.listViewSongs.SelectedItems[0].ImageIndex = 0;
                                this.currentSong.Stop();
                                this.playing         = false;
                                this.playingCustom   = false;
                                this.buttonPlay.Text = "Play";
                            }
                            if (this.lastVolume == 100)
                            {
                                if (File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Custom Music", "Modified", this.listViewSongs.SelectedItems[0].SubItems[1].Text)))
                                {
                                    File.Delete(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Custom Music", "Modified", this.listViewSongs.SelectedItems[0].SubItems[1].Text));
                                }

                                this.listViewSongs.SelectedItems[0].SubItems[3].Text = "";
                            }
                            else
                            {
                                using (WaveFileReader reader = new WaveFileReader(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Custom Music", this.listViewSongs.SelectedItems[0].SubItems[1].Text))) {
                                    using (WaveFileWriter writer = new WaveFileWriter(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Custom Music", "Modified", this.listViewSongs.SelectedItems[0].SubItems[1].Text), reader.WaveFormat)) {
                                        float[] samples = reader.ReadNextSampleFrame();
                                        while (samples != null)
                                        {
                                            for (int i = 0; i < samples.Length; i++)
                                            {
                                                writer.WriteSample(samples[i] * ((float)this.lastVolume / 100.0f));
                                            }
                                            samples = reader.ReadNextSampleFrame();
                                        }
                                    }
                                }

                                this.listViewSongs.SelectedItems[0].SubItems[3].Text = "*";
                            }
                        }
                    }
                }
            }
        }
Пример #2
0
        /// <summary>指定したパーセンテージで音量を増減させた新しいwavデータを生成します。</summary>
        /// <param name="wav">元のwavデータ</param>
        /// <param name="factorPercent">音量のパーセンテージ(0~200くらいを想定)</param>
        /// <returns>音量を変更したあとのwavデータ</returns>
        public static byte[] ChangeVolume(byte[] wav, int factorPercent)
        {
            var result = new byte[wav.Length];

            using (var msIn = new MemoryStream(wav))
                using (var fr = new WaveFileReader(msIn))
                    using (var msOut = new MemoryStream(result))
                        using (var fw = new WaveFileWriter(msOut, fr.WaveFormat))
                        {
                            var allVolumes = new List <float>();
                            while (fr.CurrentTime < fr.TotalTime)
                            {
                                var vs = fr.ReadNextSampleFrame();
                                foreach (var v in vs)
                                {
                                    allVolumes.Add(v);
                                }
                            }

                            fw.WriteSamples(
                                allVolumes.Select(v => v * factorPercent / 100.0f).ToArray(),
                                0,
                                allVolumes.Count
                                );
                        }

            return(result);
        }
Пример #3
0
        /// <summary>
        /// determine where is the trash time to cut
        /// </summary>
        /// <param name="wave">source</param>
        /// <returns>TimeSpan</returns>
        public TimeSpan DetermineTrashWave(WaveFileReader wave)
        {
            int bytesPerMillisecond = wave.WaveFormat.AverageBytesPerSecond / 1000;

            wave.Position = 0;
            int count = 0, maxcount = 0;

            float[] frameRead;
            while ((frameRead = wave.ReadNextSampleFrame()) != null)
            {
                count++;
                if (count > maxcount)
                {
                    maxcount = count;
                }
                foreach (var i in frameRead)
                {
                    if (Math.Abs(i - 0) > 1e-6)
                    {
                        count = 0;
                        break;
                    }
                }
                if (count > wave.WaveFormat.SampleRate * 0.7)
                {
                    return(wave.CurrentTime);
                }
            }
            return(TimeSpan.FromMilliseconds(0));
        }
Пример #4
0
        public AudioChunk(Stream wavFileStream)
        {
            List <float[]> buffers = new List <float[]>();
            int            length  = 0;

            using (WaveFileReader reader = new WaveFileReader(wavFileStream))
            {
                SampleRate = reader.WaveFormat.SampleRate;
                while (reader.Position < reader.Length)
                {
                    float[] data = reader.ReadNextSampleFrame();
                    if (data == null)
                    {
                        break;
                    }
                    length += data.Length;
                    buffers.Add(data);
                }
            }

            Data = new short[length];
            int   cursor = 0;
            float scale  = (float)(short.MaxValue);

            foreach (float[] chunk in buffers)
            {
                for (int c = 0; c < chunk.Length; c++)
                {
                    Data[cursor + c] = (short)(chunk[c] * scale);
                }
                cursor += chunk.Length;
            }
            wavFileStream.Close();
        }
Пример #5
0
        private void ReadSong()
        {
            using (WaveFileReader reader = new WaveFileReader(FilePath))
            {
                Samples         = new float[reader.SampleCount];
                reader.Position = 0;

                for (int i = 0; i < Samples.Length; i++)
                {
                    var frame = reader.ReadNextSampleFrame();

                    float temp = 0;

                    if (frame != null && frame.Length > 0)
                    {
                        for (int j = 0; j < frame.Length; j++)
                        {
                            temp += frame[j];
                        }

                        temp /= frame.Length;
                    }

                    Samples[i] = temp;
                }
            }
        }
Пример #6
0
        public void Draw(WaveFileReader wavReader)
        {
            _canvas.Children.Clear();
            _bitmapWrapper = new BitmapWrapper(_canvas.ActualWidth, _canvas.ActualHeight);
            //            _horizontalScale = (int)(wavReader.Length / wavReader.WaveFormat.SampleRate / FFT_SAMPLE_SIZE);
            xPos = 0;

            wavReader.Position = 0;
            for (int i = 0; i < wavReader.SampleCount; i++)
            {
                float[] sampleFrame = wavReader.ReadNextSampleFrame();
                foreach (float sampleValue in sampleFrame)
                {
                    float filteredValue = FilterValue(sampleValue);
                    //                    _sampleAggregator.Add(filteredValue);
                }
            }

            using (var fileStream = new FileStream("temp.bmp", FileMode.Create))
            {
                var pngBitmapEncoder = new PngBitmapEncoder();
                pngBitmapEncoder.Frames.Add(BitmapFrame.Create(_bitmapWrapper.Bitmap));
                pngBitmapEncoder.Save(fileStream);
            }
            _canvas.Children.Add(new Image {
                Source = _bitmapWrapper.Bitmap
            });
        }
        public static void Main(string[] args)
        {
            var speechLanguageInfos = CognitiveTranslatorService.GetSpeechLanguageInfo();
            var readOnlyCollection  = CognitiveTranslatorService.GetSpeechTextInfo();
            var speechTtsInfos      = CognitiveTranslatorService.GetSpeechTtsInfo();

            var service = new CognitiveTranslatorService(SUNSCRIPTION_KEY);

            //TODO: Modify Translate Language settings.
            service.InitializeTranslatorService("en", "ja", "ja-JP-Watanabe");
            service.OnOpen         += OnOpen;
            service.OnError        += OnError;
            service.OnRootMessage  += OnRootMessage;
            service.OnVoiceMessage += OnVoiceMessage;
            service.OnTextMessage  += OnTextMessage;

#if DEBUG
            service.LogLevel = LogLevel.Trace;
#endif

            service.StartStreaming();

            Thread.Sleep(1000);

            _thread = new Thread(() =>
            {
                //TODO: change file name.sampling rate-16Khz 16bit 1channel.
                using (var reader = new WaveFileReader("something.wav"))
                {
                    Thread.Sleep(1000);
                    var samplesL = new float[reader.Length / reader.BlockAlign];
                    for (var i = 0; i < samplesL.Length; i++)
                    {
                        var sample = reader.ReadNextSampleFrame();

                        var bytes = BitConverter.GetBytes(FloatToInt16(sample[0]));
                        service.AddSamples(bytes, 0, bytes.Length);
                    }
                    for (int i = 0; i < 32000; i++)
                    {
                        service.AddSamples(new byte[] { 0, 0 }, 0, 2);
                    }
                }
            });
            _thread.Start();

            _thread2 = new Thread(new ThreadStart(() =>
            {
                Console.ReadLine(); service.StopStreaming(); Thread.Sleep(1000); Environment.Exit(0);
            }));
            _thread2.Start();
            while (true)
            {
            }
        }
Пример #8
0
        public void CanCreateReaderForStreamWithDataChunkGreaterThan2GB()
        {
            const int  sampleBlockCount       = Int32.MaxValue / (1024 * 3);
            const int  channels               = 2;
            const uint samplesPerBlock        = 1024U * channels;
            const int  bitsPerSample          = 16;
            const uint bytesPerBlock          = samplesPerBlock * (bitsPerSample / 8);
            const uint dataChunkLengthInBytes = sampleBlockCount * bytesPerBlock;

            Assert.IsTrue(dataChunkLengthInBytes > Int32.MaxValue && dataChunkLengthInBytes <= UInt32.MaxValue,
                          "Something is wrong with the test set-up parameters.");
            using (var reader = new WaveFileReader(new LargeWaveStream(dataChunkLengthInBytes, new WaveFormat(8000, bitsPerSample, channels), new[] { 0.1f, 0.2f })))
            {
                // Check the values in the first block.
                for (int i = 0; i < 1024; i++)
                {
                    var f1 = reader.ReadNextSampleFrame();
                    Assert.AreEqual(0.1f, f1[0], 0.0001f);
                    Assert.AreEqual(0.2f, f1[1], 0.0001f);
                }

                // Read the rest of the blocks in large chunks, except for the last one
                byte[] dataToReadAndIgnore = new byte[bytesPerBlock];
                for (int i = 0; i < sampleBlockCount - 2; i++)
                {
                    Assert.AreEqual(dataToReadAndIgnore.Length,
                                    reader.Read(dataToReadAndIgnore, 0, dataToReadAndIgnore.Length),
                                    "Failed to read block " + i + 1);
                }

                // Check the values in the last block.
                for (int i = 0; i < 1024; i++)
                {
                    var f1 = reader.ReadNextSampleFrame();
                    Assert.AreEqual(0.1f, f1[0], 0.0001f);
                    Assert.AreEqual(0.2f, f1[1], 0.0001f);
                }

                // Make sure there's no more data
                Assert.AreEqual(0, reader.Read(dataToReadAndIgnore, 0, 4));
            }
        }
        public void CanAccessSamplesIndividuallyInAMonoFile()
        {
            var ms = new MemoryStream();

            using (var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(8000, 16, 1)))
            {
                writer.WriteSample(0.1f);
                writer.WriteSample(0.2f);
                writer.WriteSample(0.3f);
                writer.WriteSample(0.4f);
            }
            ms.Position = 0;
            using (var reader = new WaveFileReader(ms))
            {
                Assert.AreEqual(0.1f, reader.ReadNextSampleFrame()[0], 0.001f);
                Assert.AreEqual(0.2f, reader.ReadNextSampleFrame()[0], 0.001f);
                Assert.AreEqual(0.3f, reader.ReadNextSampleFrame()[0], 0.001f);
                Assert.AreEqual(0.4f, reader.ReadNextSampleFrame()[0], 0.001f);
                Assert.IsNull(reader.ReadNextSampleFrame());
            }
        }
Пример #10
0
        private List <float> getWavWaveForm(WaveFileReader reader)
        {
            List <float> data = new List <float>();

            float[] buffer;

            while ((buffer = reader.ReadNextSampleFrame()) != null)
            {
                data.Add(buffer[0]);
            }
            return(data);
        }
Пример #11
0
        static void Main(string[] args)
        {
            // TODO: REPLACE IT
            var readWavFilePath  = "";
            var writeWavFilePath = "";

            using var waveReader = new WaveFileReader(readWavFilePath);
            if (waveReader.WaveFormat.Channels != 1)
            {
                Console.WriteLine("Support 1 channel wav only");
                return;
            }

            var samples = new float[waveReader.Length / waveReader.BlockAlign];

            for (var i = 0; i < samples.Length; i++)
            {
                samples[i] = waveReader.ReadNextSampleFrame()[0];
            }

            using var fvadCore = FvadBuilder.Create()
                                 .SetMode(Constants.FvadModeAggressiveness.Quality)
                                 .SetSampleRate(waveReader.WaveFormat.SampleRate)
                                 .Build();

            // per 10msec
            var samplePerMsec = waveReader.WaveFormat.SampleRate / 1000 * 10;
            var result        = Enumerable.Range(0, (int)Math.Floor(samples.Length / samplePerMsec * 1f))
                                .Select(i =>
            {
                var shortSample = samples.AsSpan(samplePerMsec * i, samplePerMsec)
                                  .ToArray()
                                  .Select(v => (short)(v * short.MaxValue))
                                  .ToArray();
                return(index: i, isActive: fvadCore.IsVoiceActive(shortSample));
            });

            foreach (var(i, active) in result)
            {
                Console.WriteLine($"index: {i}, active: {active}");
            }

            var activeSamples = result.Where(v => v.isActive)
                                .SelectMany(v => samples.AsSpan(samplePerMsec * v.index, samplePerMsec).ToArray())
                                .ToArray();

            using var waveWriter = new WaveFileWriter(writeWavFilePath, new WaveFormat(
                                                          waveReader.WaveFormat.SampleRate,
                                                          waveReader.WaveFormat.BitsPerSample,
                                                          waveReader.WaveFormat.Channels));
            waveWriter.WriteSamples(activeSamples, 0, activeSamples.Length);
        }
Пример #12
0
 public Analyzer(string fileName)
 {
     using (var file = new WaveFileReader(fileName))
     {
         ActualDataLength = file.SampleCount / file.WaveFormat.Channels;
         sound            = new float[ActualDataLength];
         for (int i = 0; i < ActualDataLength; i++)
         {
             sound[i] = file.ReadNextSampleFrame()[0];
         }
         SampleRate = file.WaveFormat.SampleRate;
     }
 }
Пример #13
0
        public static float[] GetMfcc(string filePath)
        {
            var wavReader = new WaveFileReader(filePath);
            var samples   = new List <float>();

            float[] sample;
            while ((sample = wavReader.ReadNextSampleFrame()) != null)
            {
                samples.AddRange(sample);
            }

            return(GetMfcc(samples.ToArray()));
        }
        public void GetSampleFrequencyAddPoints()
        {
            if (FilePath == null)
            {
                return;
            }

            Debug.WriteLine("GetSampleFrequencyAddPoints");

            PointsCount = 0;
            try
            {
                using (var wavFileReader = new WaveFileReader(FilePath))
                {
                    AudioVM.WaveFormat = wavFileReader.WaveFormat;
                    audioVM.Duration   = wavFileReader.TotalTime;

                    Aggregator.NotificationCount = (int)((AudioVM.WaveFormat.SampleRate / (1000 * scale)) * AudioVM.WaveFormat.Channels); // * 22; // 100 * 22) / 22 ;  //(int)(wavFileReader.WaveFormat.AverageBytesPerSecond * 8/2 * scale) / 100;

                    Aggregator.RaiseRestart();

                    while (true)
                    {
                        var frame = wavFileReader.ReadNextSampleFrame(); // Read(buff, 0, 400);
                        if (frame == null)
                        {
                            break;
                        }

                        foreach (var b in frame)
                        {
                            try
                            {
                                Aggregator.Add(b);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.ToString());
                            }
                        }
                    }
                }

                RaisePropertyChanged("PointsCount");
                RaisePropertyChanged("SampledFrequency");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
        public void CanAccessSamplesIndividuallyInAStereo24BitFile()
        {
            var ms = new MemoryStream();

            using (var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(44100, 24, 2)))
            {
                writer.WriteSample(0.1f);
                writer.WriteSample(0.2f);
                writer.WriteSample(0.3f);
                writer.WriteSample(0.4f);
            }
            ms.Position = 0;
            using (var reader = new WaveFileReader(ms))
            {
                var f1 = reader.ReadNextSampleFrame();
                Assert.AreEqual(0.1f, f1[0], 0.0001f);
                Assert.AreEqual(0.2f, f1[1], 0.0001f);
                var f2 = reader.ReadNextSampleFrame();
                Assert.AreEqual(0.3f, f2[0], 0.0001f);
                Assert.AreEqual(0.4f, f2[1], 0.0001f);
                Assert.IsNull(reader.ReadNextSampleFrame());
            }
        }
Пример #16
0
 private void ReadFile()
 {
     using (var reader = new WaveFileReader(openFileDialog1.FileName))
     {
         _speechFile = new float[reader.SampleCount];
         fileChart.Series[0].Points.Clear();
         for (int i = 0; i < reader.SampleCount; i++)
         {//читаем и выводим
             _speechFile[i] = reader.ReadNextSampleFrame()[0];
             fileChart.Series[0].Points.AddXY(i, _speechFile[i]);
         }
         _speechFileFormat = reader.WaveFormat;
     }
 }
Пример #17
0
 public SoundValues(string filename)
 {
     using (var reader = new WaveFileReader(filename))
     {
         SampleRate = reader.WaveFormat.SampleRate;
         Values     = new List <SoundPoint>();
         long index = 0;
         for (var i = 0; i < reader.Length / 2; i++)
         {
             var v = reader.ReadNextSampleFrame();
             Values.Add(new SoundPoint
             {
                 Value = v[0],
                 Time  = index++
             });
         }
     }
 }
Пример #18
0
        /// <summary>
        /// Gets the maximum.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>
        /// Max float value in file
        /// </returns>
        private static float GetMax(string file)
        {
            using (var reader = new WaveFileReader(file))
            {
                float[] buffer;
                float   max = 0;

                while ((buffer = reader.ReadNextSampleFrame()) != null)
                {
                    for (var n = 0; n < buffer.Length; n++)
                    {
                        max = Math.Max(max, Math.Abs(buffer[n]));
                    }
                }

                return(max);
            }
        }
Пример #19
0
        public SampleAggregator(string filePath)
        {
            WaveFileReader reader = new WaveFileReader(filePath);

            SampleCount = reader.SampleCount;
            SampleRate  = reader.WaveFormat.SampleRate;

            AmplitudeSamples = new double[SampleCount];

            float[] buffer;
            int     counter = 0;

            while ((buffer = reader.ReadNextSampleFrame())?.Length > 0)
            {
                AmplitudeSamples[counter] = buffer.Average();
                counter++;
            }
        }
Пример #20
0
        private IEnumerable <float[]> LoadSamplesWav(string aPath)
        {
            using (var reader = new WaveFileReader(aPath))
            {
                var frames = new List <float[]>();

                while (true)
                {
                    var frame = reader.ReadNextSampleFrame();

                    if (frame == null)
                    {
                        return(frames);
                    }

                    frames.Add(frame);
                }
            }
        }
Пример #21
0
        public static int[] GetVolumesDiscrete(byte[] wav, double intervalSec)
        {
            using (var ms = new MemoryStream(wav))
                using (var fr = new WaveFileReader(ms))
                {
                    var totalTime = fr.TotalTime;

                    int[] result = new int[(int)(totalTime.TotalSeconds / intervalSec)];
                    for (int i = 0; i < result.Length; i++)
                    {
                        var normalizedVolumes = new List <float>();
                        var nextIntervalStart = TimeSpan.FromSeconds((i + 1) * intervalSec);
                        if (nextIntervalStart > totalTime)
                        {
                            nextIntervalStart = totalTime;
                        }

                        while (fr.CurrentTime < nextIntervalStart)
                        {
                            float[] volumes = fr.ReadNextSampleFrame();
                            foreach (var volume in volumes)
                            {
                                normalizedVolumes.Add(volume);
                            }
                        }

                        //見ての通り二乗値を平均して平方根を取る
                        double v = Math.Sqrt(normalizedVolumes
                                             .Select(n => n * n)
                                             .Sum() / normalizedVolumes.Count
                                             );

                        result[i] = v < Thresh0 ? 0 :
                                    v < Thresh1 ? 1 :
                                    v < Thresh2 ? 2 :
                                    v < Thresh3 ? 3 :
                                    v < Thresh4 ? 4 : 5;
                    }

                    return(result);
                }
        }
Пример #22
0
        static double[] readWav(string filename, out int rate, out WaveFormat format)
        {
            WaveFileReader reader = new WaveFileReader(filename);

            format = reader.WaveFormat;
            float[]  buffer;
            double[] data    = new double[reader.SampleCount];
            int      counter = 0;

            rate = reader.WaveFormat.SampleRate;
            while ((buffer = reader.ReadNextSampleFrame()) != null)
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    data[counter++] = buffer[i];
                }
            }
            reader.Close();
            return(data);
        }
Пример #23
0
        static WaveData readWaveData(string filename)
        {
            WaveData result = new WaveData();

            using (WaveFileReader reader = new WaveFileReader(filename)) {
                result.channelSamples = new float[reader.WaveFormat.Channels][];
                for (int i = 0; i < result.channelSamples.Length; ++i)
                {
                    result.channelSamples[i] = new float[reader.SampleCount];
                }
                for (long i = 0; i < reader.SampleCount; ++i)
                {
                    float[] samples = reader.ReadNextSampleFrame();
                    for (int j = 0; j < samples.Length && j < result.channelSamples.Length; ++j)
                    {
                        result.channelSamples[j][i] = samples[j];
                    }
                }

                result.sampleRate = reader.WaveFormat.SampleRate;
            }

            return(result);
        }
Пример #24
0
        private static void PerformFFT(string path)
        {
            WaveFileReader wav = new WaveFileReader(path);

            double[] data = new double[wav.SampleCount];

            for (int i = 0; i < data.Length; i++)
            {
                float[] frame = wav.ReadNextSampleFrame();

                if (frame.Length > 1)
                {
                    data[i] = (double)(frame[0] + frame[1]) * 0.5;
                }
                else
                {
                    data[i] = (double)frame[0];
                }
            }

            Console.WriteLine("Read File Successfully");

            int windowSize = 13;

            Console.Write($"Enter window size power (def = {windowSize}): ");

            string response = Console.ReadLine();

            while (response != "" && !int.TryParse(response, out windowSize))
            {
                Console.WriteLine("Invalid input");
                response = Console.ReadLine();
            }

            windowSize = (int)Math.Pow(2, windowSize);

            int stepSize = 30;

            Console.Write($"Enter framerate (def = {stepSize}): ");

            response = Console.ReadLine();
            while (response != "" && !int.TryParse(response, out stepSize))
            {
                Console.WriteLine("Invalid input");
                response = Console.ReadLine();
            }

            stepSize = (int)Math.Ceiling((double)wav.WaveFormat.SampleRate / stepSize);

            int skip = 10;

            Console.Write($"Enter frequency bin size (def = {skip}): ");


            response = Console.ReadLine();
            while (response != "" && !int.TryParse(response, out skip))
            {
                Console.WriteLine("Invalid input");
                response = Console.ReadLine();
            }

            Console.WriteLine("Calculating samples\n");

            double[][] FFTSlices = RunFFT(data, windowSize, stepSize);

            string[] lines = new string[FFTSlices.Length + 1];
            lines[0] = wav.TotalTime.TotalSeconds.ToString();

            Console.WriteLine();

            for (int i = 0; i < FFTSlices.Length; i++)
            {
                lines[i + 1] = DoubleArrayToString(skip, FFTSlices[i]);

                if ((i + 1) % 100 == 0)
                {
                    Console.Write($"\rCopied sample {i + 1} of {FFTSlices.Length}  ");
                }
            }

            Console.Write($"\rCopied sample {FFTSlices.Length} of {FFTSlices.Length}  ");


            File.WriteAllLines(Path.Combine(Path.GetDirectoryName(path), "_" + Path.GetFileNameWithoutExtension(path) + " - Converted.txt"), lines);

            Console.WriteLine("\n\nDone! Press Enter to continue");
            Console.ReadLine();
        }
Пример #25
0
        /// <summary>
        /// 通过波形生成时间序列
        /// </summary>
        /// <param name="fileName">波形文件路径</param>
        /// <param name="timeLine">时间序列</param>
        /// <param name="fre_count">频率采样数</param>
        /// <param name="vol_count">振幅采样数</param>
        /// <param name="tick_cycle">采样周期</param>
        /// <returns>时间序列</returns>
        public TimeLine Serialize(string fileName, TimeLine timeLine, int fre_count = 1, int vol_count = 1, int tick_cycle = 1, ShowProgress showProgress = null)
        {
            try
            {
                //Read Waves
                var reader = new WaveFileReader(fileName);
                reader.Position = 0;
                #region WaveFile -> WaveNodes
                //Create WaveNodes
                var     waveNodesL = new List <WaveNode>();
                var     waveNodesR = new List <WaveNode>();
                float[] samplesL   = new float[reader.Length / reader.BlockAlign];
                float[] samplesR   = new float[reader.Length / reader.BlockAlign];
                //Get Time-related Param
                var Hz          = (int)(samplesL.Length / reader.TotalTime.TotalSeconds);
                var FperTick    = Hz / 20;
                var SampleCycle = FperTick * tick_cycle;
                var totalTick   = samplesL.Length / FperTick;
                //Frequency & Peak
                int[]   Fre  = new int[] { /* left */ 0, /* right */ 0 };
                float[] Peak = new float[] { /* left_min */ 0, /* right_min */ 0, /* left_max */ 0, /* right_max */ 0 };
                #region Set Nodes'
                //Foreach Frequency & Peak in WaveFile
                int _temp = -1; /* Set Total Progress */ timeLine.totalProgress = samplesL.Length;
                for (int i = 0; i < samplesL.Length; i++)
                {
                    //Get Sample
                    float[] sample = reader.ReadNextSampleFrame();
                    samplesL[i] = sample[0]; //Mono - Right
                    samplesR[i] = sample[1]; //Stereo - Left
                    //Get Frequency & Peak
                    if (i > 0)
                    {
                        //Get Frequency
                        if (samplesL[i] * samplesL[i - 1] < 0)
                        {
                            Fre[0]++;
                        }
                        if (samplesR[i] * samplesR[i - 1] < 0)
                        {
                            Fre[1]++;
                        }
                        //Get Peak
                        if (samplesL[i] < Peak[0])
                        {
                            Peak[0] = samplesL[i];
                        }
                        else if (samplesL[i] > Peak[1])
                        {
                            Peak[1] = samplesL[i];
                        }
                        if (samplesR[i] < Peak[2])
                        {
                            Peak[2] = samplesR[i];
                        }
                        else if (samplesR[i] > Peak[3])
                        {
                            Peak[3] = samplesR[i];
                        }

                        //Creat Objects
                        int v = (i - 1) % SampleCycle;
                        int g = (i - 1) % FperTick;
                        int t = (i - 1) / FperTick;
                        if (v == 0)
                        {
                            waveNodesL.Add(new WaveNode()
                            {
                                TickStart = t,
                                IsLeft    = true
                            });
                            waveNodesR.Add(new WaveNode()
                            {
                                TickStart = t,
                                IsLeft    = false
                            });
                            _temp = t;
                        }
                        else if (g == 0)
                        {
                            waveNodesL.Add(new WaveNode()
                            {
                                TickStart = t,
                                IsLeft    = true
                            });
                            waveNodesR.Add(new WaveNode()
                            {
                                TickStart = t,
                                IsLeft    = false
                            });
                        }
                        //Write To Nodes
                        float ft = (float)SampleCycle / fre_count;
                        float vt = (float)SampleCycle / vol_count;
                        if (v % ft < 1)
                        {
                            waveNodesL[_temp].Param["FrequencyPerTick"].Add(new _Node_INT()
                            {
                                Name = "Fre", Value = Fre[0]
                            });
                            waveNodesR[_temp].Param["FrequencyPerTick"].Add(new _Node_INT()
                            {
                                Name = "Fre", Value = Fre[1]
                            });
                            Fre[0] = 0; Fre[1] = 0;
                        }
                        if (v % vt < 1)
                        {
                            waveNodesL[_temp].Param["VolumePerTick"].Add(new _Node_INT()
                            {
                                Name = "Vol", Value = (int)((Peak[1] - Peak[0]) * 1000)
                            });
                            waveNodesR[_temp].Param["VolumePerTick"].Add(new _Node_INT()
                            {
                                Name = "Vol", Value = (int)((Peak[3] - Peak[2]) * 1000)
                            });
                            Peak[0] = 0; Peak[1] = 0; Peak[2] = 0; Peak[3] = 0;
                        }
                    }
                    /* Update Current Progress */ timeLine.currentProgress++; if (showProgress != null && timeLine.totalProgress > 0)
                    {
                        showProgress((double)timeLine.currentProgress / timeLine.totalProgress);
                    }
                }
                #endregion
                #endregion
                #region WaveNodes -> TickNodes
                //Creat and Set Lenth of TickNodes
                if (timeLine.TickNodes == null)
                {
                    timeLine.TickNodes = new List <TickNode>();
                }
                if (totalTick >= timeLine.TickNodes.Count)
                {
                    var nowCount = timeLine.TickNodes.Count;
                    for (int i = 0; i < totalTick - nowCount + 1; i++)
                    {
                        timeLine.TickNodes.Add(new TickNode());
                    }
                }
                //WaveNodes -> TickNodes
                foreach (WaveNode waveNodeL in waveNodesL)
                {
                    if (timeLine.TickNodes[waveNodeL.TickStart].WaveNodesLeft == null)
                    {
                        timeLine.TickNodes[waveNodeL.TickStart].WaveNodesLeft = new List <WaveNode>();
                    }
                    timeLine.TickNodes[waveNodeL.TickStart].WaveNodesLeft.Add(waveNodeL);
                }
                foreach (WaveNode waveNodeR in waveNodesR)
                {
                    if (timeLine.TickNodes[waveNodeR.TickStart].WaveNodesRight == null)
                    {
                        timeLine.TickNodes[waveNodeR.TickStart].WaveNodesRight = new List <WaveNode>();
                    }
                    timeLine.TickNodes[waveNodeR.TickStart].WaveNodesRight.Add(waveNodeR);
                }
                #endregion
                timeLine.Param["TotalTicks"].Value = timeLine.TickNodes.Count;
                return(timeLine);
            }
            catch
            {
                return(null);
            }
        }
Пример #26
0
        public static void AppendWork(Stream OutputStream, Stream InputStream, double offset, double length,
                                      double ovr, List <KeyValuePair <double, double> > KV, double droptime, uint HeadLength = 0)
        {
            //Init
            WaveFormat   outputFormat = new WaveFormat(44100, 1);
            FormatHelper fhelper      = new FormatHelper(outputFormat);
            MathHelper   mhelper      = new MathHelper();


            //IOInit
            WaveFileReader ifh = null;

            try { ifh = new WaveFileReader(InputStream); }
            catch {; }
            IOHelper ofh = new IOHelper(OutputStream, outputFormat, HeadLength);

            //Prepare
            OutputStream.Seek(0, SeekOrigin.End);
            int outputFrames  = fhelper.Ms2Samples(length);
            int overlapFrames = fhelper.Ms2Samples(ovr);
            int offsetFrames  = fhelper.Ms2Samples(offset);
            List <MathHelper.SegmentLine> EnvlopeLines = fhelper.KV2SegmentLines(outputFrames, KV);

            //CheckDelay
            int dropFrames = fhelper.Ms2Samples(droptime);

            if (dropFrames < 0)
            {
                dropFrames = 0;
            }
            if (dropFrames > 0)
            {
                if (dropFrames > outputFrames - overlapFrames)
                {
                    return;
                }
            }

            //SeekInput
            if (ifh != null)
            {
                if (offsetFrames > 0)
                {
                    ifh.Seek(fhelper.Samples2Bytes((uint)offsetFrames), SeekOrigin.Begin);
                }
                else
                {
                    ifh.Seek(0, SeekOrigin.Begin);
                }
            }


            //SetWritePoint
            if (overlapFrames > 0)
            {
                long seekMap = fhelper.Samples2Bytes((uint)overlapFrames);
                if (OutputStream.Length >= seekMap)
                {
                    OutputStream.Seek((-1) * seekMap, SeekOrigin.End);
                }
            }
            else if (overlapFrames < 0)
            {
                OutputStream.Seek(0, SeekOrigin.End);
                for (int i = 0; i < -overlapFrames; i++)
                {
                    if (dropFrames > 0)
                    {
                        dropFrames--;
                    }
                    else
                    {
                        ofh.WriteSample(0.0f);
                    }
                }
                overlapFrames = 0;
            }
            for (int currentFrame = 0; currentFrame < outputFrames; currentFrame++)
            {
                float[] SampleFrame = new float[1] {
                    0.0f
                };

                if (ifh != null && ifh.Position < ifh.Length)
                {
                    SampleFrame = ifh.ReadNextSampleFrame();
                    if (SampleFrame == null)
                    {
                        SampleFrame = new float[1] {
                            0.0f
                        };
                    }
                }
                float SampleMono = SampleFrame.Length == 1 ? SampleFrame[0] : mhelper.floatAverage(SampleFrame);
                if (SampleMono != 0)
                {
                    //修复:切断音
                    double percent = MathHelper.SegmentLine.SegmentsGraphic(EnvlopeLines, currentFrame);
                    SampleMono = (float)(SampleMono * (percent / 100.0));
                }


                //OverFloat
                if (overlapFrames > 0)
                {
                    float oldFrame = 0.0f;

                    if (ofh.Position < ofh.Length && ofh.Length > 0)
                    {
                        float[] oft = ofh.ReadNextSampleFrame();
                        oldFrame = oft[0];
                        OutputStream.Seek(-1 * fhelper.Samples2Bytes(1), SeekOrigin.Current);
                        overlapFrames--;
                        float a2        = fhelper.FramesMix(SampleMono, oldFrame);
                        float SampleMix = a2;
                        if (dropFrames > 0)
                        {
                            ofh.WriteSample(oldFrame);//放弃Seek
                            dropFrames--;
                        }
                        else
                        {
                            ofh.WriteSample(SampleMix);
                        }
                    }
                    else
                    {
                        if (dropFrames > 0)
                        {
                            dropFrames--;
                        }
                        else
                        {
                            ofh.WriteSample(SampleMono);
                        }
                        overlapFrames = 0;
                    }
                }
                else
                {
                    if (dropFrames > 0)
                    {
                        dropFrames--;
                    }
                    else
                    {
                        ofh.WriteSample(SampleMono);
                    }
                }
            }
        }
Пример #27
0
 public Play(string file)
 {
     WaveFileReader reader = new WaveFileReader(file);
     sampleBuffer = new double[reader.Length];
     float[] buffer;
     while ((buffer = reader.ReadNextSampleFrame()) != null)
     {
         for (int i = 0; i < buffer.Length; i++)
         {
             sampleBuffer[n++] = buffer[i];
         }
     }
     WaveFormat format = reader.WaveFormat;
     ch = format.Channels;
     frame = sampleBuffer.Length / ch;
     n = 0;
     speed = 1;
 }
    FadeWeave(string _outfilename,
              params string [] _inpatterns)
    {
        WaveFileWriter output     = null;
        WaveFormat     waveformat = null;

        float [] sample    = null;
        float    volume    = 1.0f;
        float    volumemod = 0.0f;
        // Add .wav extension to the output if not specified.
        string extension = Path.GetExtension(_outfilename);

        if (string.Compare(extension, ".wav", true) != 0)
        {
            _outfilename += ".wav";
        }
        // Assume we're using the current directory.  Let's get the
        // list of filenames.
        List <string> filenames = new List <string>();

        foreach (string pattern in _inpatterns)
        {
            filenames.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), pattern));
        }
        try
        {
            // Alrighty.  Let's march over them.  We'll index them (rather than
            // foreach'ing) so that we can monitor first/last file.
            for (int index = 0; index < filenames.Count; ++index)
            {
                // Grab the file and use an 'audiofilereader' to load it.
                string filename = filenames[index];
                using (WaveFileReader reader = new WaveFileReader(filename))
                {
                    // Get our first/last flags.
                    bool firstfile = (index == 0);
                    bool lastfile  = (index == filenames.Count - 1);
                    // If it's the first...
                    if (firstfile)
                    {
                        // Initialize the writer.
                        waveformat = reader.WaveFormat;
                        output     = new WaveFileWriter(_outfilename, waveformat);
                    }
                    else
                    {
                        // All files must have a matching format.
                        if (!reader.WaveFormat.Equals(waveformat))
                        {
                            throw new InvalidOperationException("Different formats");
                        }
                    }
                    long fadeinsamples = 0;
                    if (!firstfile)
                    {
                        // Assume 1 second of fade in, but set it to total size
                        // if the file is less than one second.
                        fadeinsamples = waveformat.SampleRate;
                        if (fadeinsamples > reader.SampleCount)
                        {
                            fadeinsamples = reader.SampleCount;
                        }
                    }
                    // Initialize volume and read from the start of the file to
                    // the 'fadeinsamples' count (which may be 0, if it's the first
                    // file).
                    volume    = 0.0f;
                    volumemod = 1.0f / (float)fadeinsamples;
                    int sampleix = 0;
                    while (sampleix < (long)fadeinsamples)
                    {
                        sample = reader.ReadNextSampleFrame();
                        for (int floatix = 0; floatix < waveformat.Channels; ++floatix)
                        {
                            sample[floatix] = sample[floatix] * volume;
                        }
                        // Add modifier to volume.  We'll make sure it isn't over
                        // 1.0!
                        if ((volume = (volume + volumemod)) > 1.0f)
                        {
                            volume = 1.0f;
                        }
                        // Write them to the output and bump the index.
                        output.WriteSamples(sample, 0, sample.Length);
                        ++sampleix;
                    }
                    // Now for the time between fade-in and fade-out.
                    // Determine when to start.
                    long fadeoutstartsample = reader.SampleCount;
                    //if( !lastfile )
                    {
                        // We fade out every file except the last.  Move the
                        // sample counter back by one second.
                        fadeoutstartsample -= waveformat.SampleRate;
                        if (fadeoutstartsample < sampleix)
                        {
                            // We've actually crossed over into our fade-in
                            // timeframe.  We'll have to adjust the actual
                            // fade-out time accordingly.
                            fadeoutstartsample = reader.SampleCount - sampleix;
                        }
                    }
                    // Ok, now copy everything between fade-in and fade-out.
                    // We don't mess with the volume here.
                    while (sampleix < (int)fadeoutstartsample)
                    {
                        sample = reader.ReadNextSampleFrame();
                        output.WriteSamples(sample, 0, sample.Length);
                        ++sampleix;
                    }
                    // Fade out is next.  Initialize the volume.  Note that
                    // we use a bit-shorter of a time frame just to make sure
                    // we hit 0.0f as our ending volume.
                    long samplesleft = reader.SampleCount - fadeoutstartsample;
                    volume    = 1.0f;
                    volumemod = 1.0f / ((float)samplesleft * 0.95f);
                    // And loop over the reamaining samples
                    while (sampleix < (int)reader.SampleCount)
                    {
                        // Grab a sample (one float per channel) and adjust by
                        // volume.
                        sample = reader.ReadNextSampleFrame();
                        for (int floatix = 0; floatix < waveformat.Channels; ++floatix)
                        {
                            sample[floatix] = sample[floatix] * volume;
                        }
                        // Subtract modifier from volume.  We'll make sure it doesn't
                        // accidentally go below 0.
                        if ((volume = (volume - volumemod)) < 0.0f)
                        {
                            volume = 0.0f;
                        }
                        // Write them to the output and bump the index.
                        output.WriteSamples(sample, 0, sample.Length);
                        ++sampleix;
                    }
                }
            }
        }
        catch (Exception _ex)
        {
            Console.WriteLine("Exception: {0}", _ex.Message);
        }
        finally
        {
            if (output != null)
            {
                try{ output.Dispose(); } catch (Exception) {}
            }
        }
    }
Пример #29
0
        public Converter()
        {
            Task.Run(async() =>
            {
                while (true)
                {
                    var reader = converter.Reader;
                    while (await reader.WaitToReadAsync())
                    {
                        while (reader.TryRead(out var filePath))
                        {
                            this.RaiseProgressChanged(0);
                            this.Converting = true;
                            try
                            {
                                var left         = new List <double>();
                                var right        = new List <double>();
                                var isStereo     = false;
                                var samplingTime = 0d;

                                var allProgress = 0L;
                                var progress    = 0L;
                                void NotifyProgress() => this.RaiseProgressChanged((int)(100 * progress++ / allProgress));

                                using (var waveReader = new WaveFileReader(filePath))
                                {
                                    isStereo     = waveReader.WaveFormat.Channels == 2;
                                    samplingTime = 1d / waveReader.WaveFormat.SampleRate;

                                    allProgress = waveReader.SampleCount * 2;

                                    while (true)
                                    {
                                        var signals = waveReader.ReadNextSampleFrame();
                                        if (signals == null)
                                        {
                                            break;
                                        }
                                        left.Add(signals[0]);
                                        if (isStereo)
                                        {
                                            right.Add(signals[1]);
                                        }

                                        NotifyProgress();
                                    }
                                }

                                var builder = new StringBuilder();
                                using (var textWriter = new StringWriter(builder))
                                    using (var csvWriter = new CsvWriter(textWriter))
                                    {
                                        csvWriter.WriteField("Time");
                                        csvWriter.WriteField("Left");
                                        if (isStereo)
                                        {
                                            csvWriter.WriteField("Right");
                                        }
                                        csvWriter.NextRecord();

                                        for (int i = 0; i < left.Count; i++)
                                        {
                                            var time = i * samplingTime;
                                            csvWriter.WriteField(time);

                                            csvWriter.WriteField(left[i]);
                                            if (isStereo)
                                            {
                                                csvWriter.WriteField(right[i]);
                                            }
                                            csvWriter.NextRecord();

                                            NotifyProgress();
                                        }
                                    }

                                var csvFilePath = Path.ChangeExtension(filePath, "csv");
                                if (File.Exists(csvFilePath))
                                {
                                    File.Delete(csvFilePath);
                                }
                                File.WriteAllText(csvFilePath, builder.ToString());
                            }
                            catch (Exception ex)
                            {
                                this.RaiseFailed(ex);
                            }
                            finally
                            {
                                this.RaiseProgressChanged(100);
                                this.Converting = false;
                            }
                        }
                    }
                }
            });
        }