Exemplo n.º 1
0
        private void PlayBtn_Click(object sender, EventArgs e)
        {
            if (PlayListBox.SelectedIndex < 0)
            {
                return;
            }
            wout ??= new WaveOut();
            if (MusicNameLb.Text == Path.GetFileNameWithoutExtension(PlayListBox.SelectedItem as string))
            {
                wout.Play();
                wout.Resume();
                return;
            }

            reader?.Dispose();

            reader = new AudioFileReader(PlayListBox.SelectedItem as string);
            offsetSampleProvider = new OffsetSampleProvider(reader);
            wout.Init(offsetSampleProvider);
            wout.Play();

            wout.PlaybackStopped += (sender, e) => MusicNameLb.Text = "";

            MusicNameLb.Text     = Path.GetFileNameWithoutExtension(PlayListBox.SelectedItem as string);
            ViewModule.IsPlaying = true;
        }
Exemplo n.º 2
0
        public static bool TakeClipAddSilence(string file, TimeSpan lengthSilence, TimeSpan startTime, TimeSpan length, string newFile)
        {
            try
            {
                //byte[] buffer = new byte[1024];
                AudioFileReader      afr       = new AudioFileReader(file);
                OffsetSampleProvider offsetter = new OffsetSampleProvider(afr)
                {
                    DelayBy  = lengthSilence,
                    LeadOut  = lengthSilence,
                    SkipOver = startTime,
                    Take     = length
                };
                offsetter.ToMono();

                var provider = new SampleToWaveProvider(offsetter);

                WaveFileWriter.CreateWaveFile(newFile, provider);

                ChangeWaveFormat(newFile, 16000, 16, 1);

                return(true);
            }
            catch (Exception exc)
            {
                ErrorMessage.Raise(exc);
                return(false);
            }
        }
Exemplo n.º 3
0
        public void Cache()
        {
            using (AudioFileReader audioFileReader = new AudioFileReader(info.Path))
            {
                ISampleProvider provider = audioFileReader;

                if (info.Start != 0 || info.Length != 0)
                {
                    provider = new OffsetSampleProvider(provider)
                    {
                        SkipOver = TimeSpan.FromSeconds(info.Start),
                        Take     = info.Length == 0 ? TimeSpan.Zero : TimeSpan.FromSeconds(info.Length)
                    };
                }

                WaveFormat = provider.WaveFormat;
                List <float> wholeFile  = new List <float>((int)(audioFileReader.Length / 4));
                float[]      readBuffer = new float[provider.WaveFormat.SampleRate * provider.WaveFormat.Channels];
                int          samplesRead;
                while ((samplesRead = provider.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    wholeFile.AddRange(readBuffer.Take(samplesRead));
                }
                AudioData = wholeFile.ToArray();
            }
        }
Exemplo n.º 4
0
        private void buttonSaveSignals_Click(object sender, EventArgs e)
        {
            var samplesList = new List <ISampleProvider> {
                wg1, wg2
            };

            var mixer = new MixingSampleProvider(samplesList);

            var waveOut = new WaveOut();

            waveOut.Init(mixer);
            //waveOut.Play();

            var saveSeconds = (int)numericUpDownSaveSignalsSeconds.Value;
            var sfd         = new SaveFileDialog {
                Filter = "WAV Файл|*.wav"
            };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var osp = new OffsetSampleProvider(mixer)
            {
                TakeSamples = mixer.WaveFormat.SampleRate * saveSeconds * mixer.WaveFormat.Channels
            };

            WaveFileWriter.CreateWaveFile16(sfd.FileName, osp);
        }
Exemplo n.º 5
0
        public void WaveFormatIsSampeAsSource()
        {
            var source = new TestSampleProvider(32000, 1, 10);
            var osp    = new OffsetSampleProvider(source);

            Assert.AreEqual(source.WaveFormat, osp.WaveFormat);
        }
Exemplo n.º 6
0
        public void Play()
        {
            foreach (Movement movement in movements)
            {
                String filePath = GetSoundFile(movement.Sound.FileName);

                var file    = new AudioFileReader(filePath);
                var trimmed = new OffsetSampleProvider(file);
                trimmed.SkipOver = TimeSpan.FromMilliseconds(movement.SkipOver);
                //  trimmed.Take = TimeSpan.FromMilliseconds(movement.Sound.Time);

                var player = new WaveOutEvent();
                player.Init(trimmed);


                long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

                Debug.WriteLine("Play " + JsonConvert.SerializeObject(movement), Convert.ToString(milliseconds));
                player.Play();

                System.Threading.Thread.Sleep(Miliseconds(movement.Sound.Centiseconds));

                player.Stop();
                Debug.WriteLine("Stop ");
            }
        }
Exemplo n.º 7
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            var file    = new AutoDisposeFileReader(new AudioFileReader(FileName));
            var trimmed = new OffsetSampleProvider(file);
            int totrim  = pwfc.WaveFormDisplay.Values.First(n => n.Value.Item1 > NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold) && n.Value.Item2 < NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold)).Key;

            pwfc.SelectionStart = pwfc.XLocationToTimeSpan(pwfc.WaveFormDisplay.Values.First(n => n.Value.Item1 > NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold) && n.Value.Item2 < NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold)).Key);
            pwfc.SelectionEnd   = pwfc.XLocationToTimeSpan(pwfc.WaveFormDisplay.Values.Reverse().First(n => n.Value.Item1 > NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold) && n.Value.Item2 < NAudio.Utils.Decibels.DecibelsToLinear(SilenceThreshold)).Key);
            pwfc.DrawSelectionRect();

            trimmed.SkipOver = TimeSpan.Zero;
            trimmed.Take     = pwfc.SelectionEnd;

            WaveFileWriter.CreateWaveFile(@"c:\temp\trimmed.wav", new SampleToWaveProvider(trimmed));
            pwfc.ClearWaveForm();
            pwfc.AddNewWaveForm(Color.FromRgb(67, 217, 150), SampleRate, BitsPerSample, Channels);

            FileName = @"c:\temp\trimmed.wav";

            MemoryStream ms    = new MemoryStream(File.ReadAllBytes(FileName));
            var          file2 = new WaveFileReader(ms);

            new Task(() =>
            {
                var player = new WaveOutEvent();
                player.Init(file2);
                player.Play();
                while (player.PlaybackState != PlaybackState.Stopped)
                {
                    System.Threading.Thread.Sleep(100);
                }
                file2.Close();
            }).Start();
        }
Exemplo n.º 8
0
        private static void ApplyOffset(ISampleProvider[] providers, double spacingDuration, bool isMp3)
        {
            for (int i = 0; i < providers.Length; i++)
            {
                ISampleProvider sampleProvider = providers[i];

                OffsetSampleProvider offsetSampleProvider = new OffsetSampleProvider(sampleProvider);
                if (i == 0 && isMp3)
                {
                    // reduce padding to offset that delay .mp3 files have at the start
                    offsetSampleProvider.DelayBy = TimeSpan.FromSeconds(spacingDuration - Mp3Delay);
                }
                else
                {
                    offsetSampleProvider.DelayBy = TimeSpan.FromSeconds(spacingDuration);
                }
                if (i == providers.Length - 1)
                {
                    // pad out end of the audio sprite too.
                    offsetSampleProvider.LeadOut = TimeSpan.FromSeconds(spacingDuration);
                }

                providers[i] = offsetSampleProvider;
            }
        }
Exemplo n.º 9
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var file    = new AudioFileReader(FileName);
            var trimmed = new OffsetSampleProvider(file);

            trimmed.SkipOver = pwfc.SelectionStart;
            trimmed.Take     = pwfc.SelectionEnd - pwfc.SelectionStart;

            WaveFileWriter.CreateWaveFile(@"c:\temp\trimmed.wav", new SampleToWaveProvider(trimmed));
            pwfc.ClearWaveForm();
            pwfc.AddNewWaveForm(Color.FromRgb(67, 217, 150), SampleRate, BitsPerSample, Channels);

            FileName = @"c:\temp\trimmed.wav";
            MemoryStream ms    = new MemoryStream(File.ReadAllBytes(FileName));
            var          file2 = new WaveFileReader(ms);

            new Task(() =>
            {
                var player = new WaveOutEvent();
                player.Init(file2);
                player.Play();
                while (player.PlaybackState != PlaybackState.Stopped)
                {
                    System.Threading.Thread.Sleep(100);
                }
                file2.Close();
            }).Start();
        }
Exemplo n.º 10
0
        public IEnumerable <ISampleProvider> CreateArpeggioSamples(IEnumerable <int> chordKeyNumbers, int length, double speed)
        {
            if (!chordKeyNumbers.Any())
            {
                return(null);
            }

            List <ISampleProvider> arpeggioInputs = new List <ISampleProvider>();

            for (int i = 0; i <= length; i++)
            {
                foreach (var num in chordKeyNumbers)
                {
                    var squareWave = new SignalGenerator()
                    {
                        Gain      = 0.12,
                        Frequency = MusicalMathHelper.CalculateFrequency(num, 4),
                        Type      = SignalGeneratorType.Square
                    };

                    var trimmed             = new OffsetSampleProvider(squareWave);
                    var trimmedWithTimeSpan = trimmed.Take(TimeSpan.FromSeconds(speed));
                    arpeggioInputs.Add(trimmedWithTimeSpan);
                }
            }

            return(arpeggioInputs);
        }
Exemplo n.º 11
0
        public void DefaultShouldPassStraightThrough()
        {
            var source = new TestSampleProvider(32000, 1);
            var osp    = new OffsetSampleProvider(source);

            var expected = new float[] { 0, 1, 2, 3, 4, 5, 6 };

            osp.AssertReadsExpected(expected);
        }
Exemplo n.º 12
0
        public void CantSetNonBlockAlignedLeadOutSamples()
        {
            var source = new TestSampleProvider(32000, 2);
            var osp    = new OffsetSampleProvider(source);

            var ex = Assert.Throws <ArgumentException>(() => osp.LeadOutSamples = 3);

            Assert.That(ex.Message.Contains("LeadOutSamples"));
        }
        /// <summary>
        /// Concatenates one Sample Provider on the end of another with silence inserted
        /// </summary>
        /// <param name="sampleProvider">The sample provider to play first</param>
        /// <param name="silenceDuration">Silence duration to insert between the two</param>
        /// <param name="next">The sample provider to play next</param>
        /// <returns>A single sample provider</returns>
        public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, TimeSpan silenceDuration, ISampleProvider next)
        {
            var silenceAppended = new OffsetSampleProvider(sampleProvider)
            {
                LeadOut = silenceDuration
            };

            return(new ConcatenatingSampleProvider(new[] { silenceAppended, next }));
        }
Exemplo n.º 14
0
        private void playSentence(int n)
        {
            if (audioFile == null)
            {
                return;
            }
            if (n <= 0 || n > nMax - 1)
            {
                return;
            }

            outputDevice.Pause();
            iPlayAll = false;

            timer1.Stop();

            outputDevice.Dispose();

            // 前回、赤色に変えた文字を黒に戻す
            richTextBox1.Select(previousTotalLength - previousSentenceLength, previousSentenceLength);
            richTextBox1.SelectionColor = Color.Black;

            int startToPauseTimeMS = pauseTimeMS[n] - startTimeMS[n];

            if (startToPauseTimeMS <= 0)
            {
                MessageBox.Show("このセンテンスのタイムタグは不正です。");
                return;
            }


            int totalLength = 0;    // 文頭から再生するセンテンスまでのトータルの文字数を入れる変数

            for (int m = 0; m < n + 1; m++)
            {
                totalLength = totalLength + sentences[m].Length;
            }
            // 再生箇所を赤色に変える
            richTextBox1.Select(totalLength - sentences[n].Length, sentences[n].Length);
            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.Select(totalLength, 0);

            previousTotalLength    = totalLength;
            previousSentenceLength = sentences[n].Length;


            audioFile.CurrentTime = TimeSpan.FromSeconds(startTimeMS[n] / 1000.0);

            offsetSample      = new OffsetSampleProvider(audioFile);
            offsetSample.Take = TimeSpan.FromSeconds(startToPauseTimeMS / 1000.0);

            outputDevice.Init(offsetSample);
            timer1.Start();

            outputDevice.Play();
            playButton.Image = Properties.Resources.pause;
        }
Exemplo n.º 15
0
        public void CantSetTakeSamplesAfterCallingRead()
        {
            var source = new TestSampleProvider(32000, 1);
            var osp    = new OffsetSampleProvider(source);
            var buffer = new float[10];

            osp.Read(buffer, 0, buffer.Length);

            Assert.Throws <InvalidOperationException>(() => osp.TakeSamples = 4);
        }
Exemplo n.º 16
0
 private void btnPlay_Click(object sender, EventArgs e)
 {
     RSS                           = new RawSourceWaveStream(sourceStream, waveSource.WaveFormat);
     RSS.Position                  = 0;
     offsetSampleProvider          = new OffsetSampleProvider(RSS.ToSampleProvider());
     offsetSampleProvider.SkipOver = TimeSpan.FromMilliseconds(0);
     offsetSampleProvider.Take     = TimeSpan.FromMilliseconds(3000);
     outputSound.Init(offsetSampleProvider);
     outputSound.Play();
 }
Exemplo n.º 17
0
        public void HandlesSkipOverEntireSourceCorrectly()
        {
            var source = new TestSampleProvider(32000, 1, 10);
            var osp    = new OffsetSampleProvider(source);

            osp.SkipOverSamples = 20;

            var expected = new float[] { };

            osp.AssertReadsExpected(expected, 20);
        }
        private static OffsetSampleProvider CreateSignalGenerator(int @from, int channels)
        {
            var signalGenerator = new SignalGenerator(@from, channels);

            signalGenerator.Type      = SignalGeneratorType.SawTooth;
            signalGenerator.Frequency = 512;
            signalGenerator.Gain      = 0.3f;
            var offset = new OffsetSampleProvider(signalGenerator);

            offset.TakeSamples = @from * channels * 5; // 5 seconds
            return(offset);
        }
        public void CanAddLeadOut()
        {
            var source = new TestSampleProvider(32000, 1, 10);
            var osp    = new OffsetSampleProvider(source)
            {
                LeadOutSamples = 5
            };

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

            osp.AssertReadsExpected(expected);
        }
Exemplo n.º 20
0
        public void CanTake()
        {
            var source = new TestSampleProvider(32000, 1);
            var osp    = new OffsetSampleProvider(source)
            {
                TakeSamples = 7
            };

            var expected = new float[] { 0, 1, 2, 3, 4, 5, 6 };

            osp.AssertReadsExpected(expected, 10);
        }
Exemplo n.º 21
0
        private void Play(string filename, int startPosition, int length)
        {
            var file    = new AudioFileReader(filename);
            var trimmed = new OffsetSampleProvider(file);

            trimmed.SkipOver = TimeSpan.FromMilliseconds(startPosition);
            trimmed.Take     = TimeSpan.FromMilliseconds(length);

            SoundPlayer = new WaveOutEvent();
            SoundPlayer.Init(trimmed);
            SoundPlayer.Play();
        }
Exemplo n.º 22
0
        public void CanSkipOver()
        {
            var source = new TestSampleProvider(32000, 1);
            var osp    = new OffsetSampleProvider(source)
            {
                SkipOverSamples = 17
            };

            var expected = new float[] { 17, 18, 19, 20, 21, 22, 23, 24 };

            osp.AssertReadsExpected(expected);
        }
Exemplo n.º 23
0
        void StartPlayback()
        {
            State = LooperState.Playing;

            button_play.Enabled          = false;
            button_StopPlayback.Enabled  = true;
            numericUpDown_length.Enabled = false;
            numericUpDown_start.Enabled  = false;

            if (File.Exists("data\\" + this.Name + "\\" + FileName))
            {
                if (reader1 == null)
                {
                    reader1        = new AudioFileReader("data\\" + this.Name + "\\" + FileName);
                    reader1.Volume = trackBar_Volume.Value / 100f;

                    sampleProvider1 = new OffsetSampleProvider(reader1);
                    parent.GetRecorder().AddTrack(sampleProvider1);
                    Logger.Log(Name + " - starting playback (reader1 first)");
                }
                else if /*(reader1.Position == reader1.Length)*/ (sampleProvider1 == null)
                {
                    reader1.Position = 0;

                    sampleProvider1 = new OffsetSampleProvider(reader1);
                    parent.GetRecorder().AddTrack(sampleProvider1);
                    Logger.Log(Name + " - starting playback (reader1 repeat)");
                }
                else if (reader2 == null)
                {
                    reader2        = new AudioFileReader("data\\" + this.Name + "\\" + FileName);
                    reader2.Volume = trackBar_Volume.Value / 100f;

                    sampleProvider2 = new OffsetSampleProvider(reader2);
                    parent.GetRecorder().AddTrack(sampleProvider2);
                    Logger.Log(Name + " - starting playback (reader2 first)");
                }
                else
                {
                    reader2.Position = 0;

                    sampleProvider2 = new OffsetSampleProvider(reader2);
                    parent.GetRecorder().AddTrack(sampleProvider2);
                    Logger.Log(Name + " - starting playback (reader2 repeat)");
                }
            }
            else
            {
                parent.GetMetronome().EmergencyStop();
                MessageBox.Show("You must first record the audio.", "File doesn't exist");
            }
        }
Exemplo n.º 24
0
 private void Looper_MixerInputEnded(object sender, SampleProviderEventArgs e)
 {
     if (e.SampleProvider == sampleProvider1)
     {
         Logger.Log(Name + " - playback ended (reader1)");
         sampleProvider1 = null;
     }
     if (e.SampleProvider == sampleProvider2)
     {
         Logger.Log(Name + " - playback ended (reader2)");
         sampleProvider2 = null;
     }
 }
Exemplo n.º 25
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            btnStop_Click(this, e);
            var sfd = new SaveFileDialog();

            sfd.Filter = "WAV File|*.wav";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var osp = new OffsetSampleProvider(wg);
                osp.TakeSamples = wg.WaveFormat.SampleRate * 20 * wg.WaveFormat.Channels;
                WaveFileWriter.CreateWaveFile16(sfd.FileName, osp);
            }
        }
Exemplo n.º 26
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     using (var reader1 = new AudioFileReader("cyrf_comeback.mp3"))
         using (var reader2 = new AudioFileReader("cyrf_crossroad_advanced.mp3"))
         {
             var trimmed = new OffsetSampleProvider(reader1)
             {
                 DelayBy = TimeSpan.FromSeconds(10),
             };
             var mixer = new MixingSampleProvider(new ISampleProvider[] { trimmed, reader2 });
             WaveFileWriter.CreateWaveFile16("mixed.wav", mixer);
         }
 }
Exemplo n.º 27
0
        public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, TimeSpan silenceDuration, ISampleProvider next)
        {
            OffsetSampleProvider offsetSampleProvider = new OffsetSampleProvider(sampleProvider)
            {
                LeadOut = silenceDuration
            };

            return(new ConcatenatingSampleProvider(new ISampleProvider[]
            {
                offsetSampleProvider,
                next
            }));
        }
Exemplo n.º 28
0
        public void PlayKey(int keyNumber)
        {
            var squareWave = new SignalGenerator()
            {
                Gain      = 0.12,
                Frequency = MusicalMathHelper.CalculateFrequency(keyNumber, 4),
                Type      = SignalGeneratorType.Square
            };

            var trimmed             = new OffsetSampleProvider(squareWave);
            var trimmedWithTimeSpan = trimmed.Take(TimeSpan.FromSeconds(0.4));

            WaveformPlayer.Instance.PlayWaveform(trimmedWithTimeSpan);
        }
Exemplo n.º 29
0
        public void SettingPreDelayUsingTimeSpanReturnsCorrectTimeSpan()
        {
            var source = new TestSampleProvider(100, 2)
            {
                Position = 10
            };
            var osp = new OffsetSampleProvider(source)
            {
                DelayBy = TimeSpan.FromSeconds(2.5)
            };

            Assert.AreEqual(2500, (int)osp.DelayBy.TotalMilliseconds);
            Assert.AreEqual(500, osp.DelayBySamples);
        }
Exemplo n.º 30
0
        private void btnOffsetProvider_Click(object sender, RoutedEventArgs e)
        {
            var sampleRate      = 44100;
            var channelCount    = 1;
            var seconds         = 10;
            var signalGenerator = new SignalGenerator(sampleRate, channelCount);

            signalGenerator.Type      = SignalGeneratorType.Sin;
            signalGenerator.Frequency = 750;
            signalGenerator.Gain      = 0.5;
            var offsetProvider = new OffsetSampleProvider(signalGenerator);

            offsetProvider.TakeSamples = sampleRate * seconds * channelCount;
            WaveFileWriter.CreateWaveFile16("sonidito.wav", offsetProvider);
        }