Beispiel #1
0
 private float[] Buffer()
 {
     float[] buffer = new float[reader.Length * 4];
     reader.ToSampleProvider().Read(buffer, 0, buffer.Length);
     reader.Position = 0;
     return(buffer);
 }
Beispiel #2
0
        /// <summary>
        /// Открытвает аудиофайл и заполняет данными (массив байтов и частота дискретизации)
        /// </summary>
        /// <param name="file"></param>
        public static void GetWaveData(ref WavFile wav)
        {
            //Чтение аудиофайла
            AudioFileReader reader = new AudioFileReader(wav.Name);

            if (reader.WaveFormat.Channels != 2)
            {
                throw new NotStereoException();
            }

            int bitsPerSample = reader.WaveFormat.BitsPerSample;

            wav.Length     = (int)(((reader.Length * 8) / bitsPerSample) / (reader.WaveFormat.SampleRate * 2));
            wav.Samplerate = reader.WaveFormat.SampleRate;
            int sampleCount = (int)((reader.Length * 8) / reader.WaveFormat.BitsPerSample);

            //Запись в массив
            reader.ToSampleProvider();
            float[] buffer = new float[(reader.Length * 8) / reader.WaveFormat.BitsPerSample];

            //Запись в структуру по левому и правому каналу
            reader.Read(buffer, 0, sampleCount);
            wav.Left  = new double[sampleCount];
            wav.Right = new double[sampleCount];

            for (int i = 0, j = 0; i < sampleCount; i += 2, ++j)
            {
                wav.Left[j]  = buffer[i];
                wav.Right[j] = buffer[i + 1];
            }
        }
Beispiel #3
0
        public void OpenAudioFile(string fileName)
        {
            this.EnsureInitialized();
            this._store.IsWorking = true;

            ThreadPool.QueueUserWorkItem(async _ =>
            {
                VoiceAnalysisResult analysisResult;
                var reader = new AudioFileReader(fileName);

                try
                {
                    analysisResult = await this._voiceAnalyzer
                                     .Analyze(this._store.VowelClassifierType, reader.ToSampleProvider())
                                     .ConfigureAwait(false);
                }
                catch
                {
                    reader.Dispose();
                    throw; // TODO: エラー処理するならここで
                }

                if (this._player != null)
                {
                    this._player.Dispose();
                }
                this._player = new PlayerModel(reader, this._store);

                this._store.VoiceAnalysisResult       = analysisResult;
                this._store.PlaybackPositionInSamples = 0;
                this._store.IsWorking = false;

                this.CalculateConcordanceRate();
            });
        }
        public static List <IList <float> > ReadChannels(string audioFilePath, out WaveFormat waveFormat)
        {
            var audioData = new List <IList <float> >();
            var buffer    = new float[1];

            using (var audioReader = new AudioFileReader(audioFilePath))
            {
                var sampleProvider = audioReader.ToSampleProvider();
                waveFormat = sampleProvider.WaveFormat;
                var channelCount = sampleProvider.WaveFormat.Channels;
                for (int channelIdx = 0; channelIdx < channelCount; channelIdx++)
                {
                    audioData.Add(new List <float>());
                }
                var offset  = 0;
                var channel = 0;
                while (sampleProvider.Read(buffer, offset, 1) > 0)
                {
                    audioData[channel].Add(buffer[0]);
                    channel++;
                    if (channel >= channelCount)
                    {
                        channel = 0;
                    }
                }
            }

            return(audioData);
        }
Beispiel #5
0
 internal NAudioTrack(NAudioPlayer player, MixingSampleProvider outputMixer, AudioFileReader inputStream, string fileName)
 {
     this.player      = player;
     this.outputMixer = outputMixer;
     this.inputStream = inputStream;
     this.fileName    = fileName;
     sampleProvider   = new SampleWrapper(inputStream.ToSampleProvider());
 }
Beispiel #6
0
        private static void UpdateCue()
        {
            Context con = new Context(true);

            if (cue.Count < 1)
            {
                return;
            }

            foreach (Audio audio in cue)
            {
                if (!audio.Prepared && !audio.Prepairing)
                {
                    con.WriteLine("Prepairing " + audio.VideoInfo() + "...");
                    Task t = new Task(() => { audio.Prepare(); new Context(true).WriteLine(audio.VideoInfo() + " is prepared"); });

                    t.Start();

                    SpinWait.SpinUntil(() => { return(audio.Prepairing | audio.Prepared); });
                }
            }

            if (current != cue[0])
            {
                Close();
                current = cue[0];

                if (current.Prepairing)
                {
                    con.WriteLine("Still prepairing File...");
                    SpinWait.SpinUntil(() => { return(!current.Prepairing); });

                    Thread.Sleep(100);

                    if (!current.Prepared)
                    {
                        con.WriteLine("There was a problem, skipping!");
                        ShiftCue();
                        return;
                    }
                }

                fileReader = new AudioFileReader(current.path);

                prov = fileReader.ToSampleProvider().ToMono().ToWaveProvider16();

                convert = new WaveFormatConversionProvider(new WaveFormat(48000, 16, 1), prov);

                read = convert.ToSampleProvider();
                fileReader.Volume = cachedVol;
            }
        }
Beispiel #7
0
        private static void BasicTest()
        {
            const int windowSize = 1024;
            int       rate;
            var       data = new float[windowSize];

            // 2.5sのところから1024サンプル取得してくる
            using (var reader = new AudioFileReader(@"C:\Users\azyob\Documents\Jupyter\chroma\BEYOND THE STARLIGHT.wav"))
            {
                var provider = reader.ToSampleProvider()
                               .Skip(TimeSpan.FromSeconds(5.2))
                               .ToMono();

                rate = provider.WaveFormat.SampleRate;

                for (var readSamples = 0; readSamples < data.Length;)
                {
                    var delta = provider.Read(data, readSamples, data.Length - readSamples);
                    if (delta == 0)
                    {
                        throw new EndOfStreamException();
                    }
                    readSamples += delta;
                }
            }

            var fft = Array.ConvertAll(data, x => (Complex)x);

            FourierTransform2.FFT(fft, FourierTransform.Direction.Forward);
            var fftSeries = new LineSeries();

            fftSeries.Points.AddRange(fft.Take(fft.Length / 2).Select((x, i) => new DataPoint(i, Math.Log(x.SquaredMagnitude()))));
            ShowPlot(new PlotModel()
            {
                Title = "スペクトル", Series = { fftSeries }
            });

            var nsdf   = McLeodPitchMethod.NormalizedSquareDifference(data);
            var series = new LineSeries();

            series.Points.AddRange(nsdf.Select((x, i) => new DataPoint(i, x)));
            ShowPlot(new PlotModel()
            {
                Title = "NSDF", Series = { series }
            });

            Console.WriteLine("{0} Hz", McLeodPitchMethod.EstimateFundamentalFrequency(rate, data));
        }
Beispiel #8
0
        //Plays a selection of media
        private void PlayClip(int index)
        {
            waveOut.Stop();
            reader.Close();

            reader  = new AudioFileReader(fileDirectory + currentSong + ".mp3");
            waveOut = new WaveOut();
            waveOut.Init(reader);

            provider        = reader.ToSampleProvider(); //Here I get the samples
            reader.Position = 0;                         //Go to the position 0 after reading the samples

            waveOut.Play();
            NowPlaying.Text = "Now Playing: " + currentSong;
            PlayBtn.Text    = "Pause";
        }
Beispiel #9
0
        public MainWindow()
        {
            InitializeComponent();

            var testFile    = @"D:\CloudMusic\TWILL - New World.flac";
            var reader      = new AudioFileReader(testFile);
            var samples     = reader.ToSampleProvider();
            var buffer      = new byte[reader.Length];
            var readedCount = reader.Read(buffer, 0, buffer.Length);
            var channels    = reader.WaveFormat.Channels;
            var sampleRate  = reader.WaveFormat.SampleRate;
            var fftsize     = 4096;
            var m           = (int)Math.Log(fftsize, 2.0);

            for (var n = 0; n < readedCount; n += channels)
            {
            }
        }
Beispiel #10
0
        public Form1()
        {
            InitializeComponent();
            //sets volume and sets the volume percent value.

            volumeBar.Value       = volumeBar.Maximum / 2;
            lblVolumePercent.Text = (volumeBar.Value.ToString() + "%");


            progressBar.Maximum = 1;

            for (int i = 0; i < files.Count; i++)
            {
                files[i] = files[i].Replace("\\", "/");
            }

            files.AddRange(System.IO.Directory.GetFiles(fileDirectory, "*.mp3"));

            for (int i = 0; i < files.Count; i++)
            {
                int start = files[i].IndexOf("/AudioFiles/") + 12;
                files[i] = files[i].Substring(start, (files[i].Length - 4) - start);
            }

            //CreatePlaylist();
            //CreateShuffleList();

            SongSelector.Items.Clear();
            SongSelector.Items.AddRange(files.ToArray());
            SongSelector.SelectedIndex = 0;

            reader  = new AudioFileReader(fileDirectory + "01 - Battery.mp3");
            waveOut = new WaveOut();
            waveOut.Init(reader);

            provider        = reader.ToSampleProvider(); //Here I get the samples
            reader.Position = 0;                         //Go to the position 0 after reading the samples

            waveOut.PlaybackStopped += (object sender, StoppedEventArgs e) =>
            {
                Console.WriteLine(e.Exception);
                NextSong();
            };
        }
Beispiel #11
0
        /// <summary>
        /// Returns a Stereobuffer class by input of a file
        /// </summary>
        /// <param name="note">note (nog nodig?)</param>
        /// <param name="file">location of audio file</param>
        /// <returns></returns>
        private StereoBuffer CreateSampleBuffer(int gridItemId, string file)
        {
            var kickbuffer = new StereoBuffer(gridItemId);

            float[] leftList = null;

            using (var reader = new AudioFileReader(file)) {
                leftList = new float[reader.Length];
                reader.ToSampleProvider().Read(leftList, 0, leftList.Length);
            }

            //readWav(file, out leftList, out richtList);
            if (leftList != null)
            {
                kickbuffer.LeftSamples  = leftList.ToList();
                kickbuffer.RightSamples = leftList.ToList();
            }

            return(kickbuffer);
        }
Beispiel #12
0
        public static IList <float> ReadMonoSamples(string audioFilePath, out int sampleRate)
        {
            var audioData = new List <float>();
            var buffer    = new float[1];

            using (var audioReader = new AudioFileReader(audioFilePath))
            {
                var sampleProvider = audioReader.ToSampleProvider();
                sampleRate = sampleProvider.WaveFormat.SampleRate;
                var channelCount = sampleProvider.WaveFormat.Channels;
                if (channelCount > 1)
                {
                    sampleProvider = sampleProvider.ToMono();
                }
                var offset = 0;
                while (sampleProvider.Read(buffer, offset, 1) > 0)
                {
                    audioData.Add(buffer[0]);
                }
            }
            return(audioData);
        }
Beispiel #13
0
        private void btn_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "MP3 File (*.mp3)|*.mp3|WAV File (*.wav)|*.wav";
            if (open.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            output = new WaveOutEvent();
            stream = new AudioFileReader(open.FileName);
            pitch  = new SmbPitchShiftingSampleProvider(stream.ToSampleProvider());

            pitch.PitchFactor = 1;
            stereo            = new MonoToStereoSampleProvider(pitch.ToMono());

            output.Init(stereo);

            stereo.RightVolume = 0.5f;
            stereo.LeftVolume  = 0.5f;
            stream.Volume      = 0.5f;

            lb_name.Text    = open.SafeFileName;
            lb_length.Text  = stream.TotalTime.ToString().Remove(8);
            lb_length.Text += " sec.";
            lb_decTime.Text = stream.CurrentTime.ToString();

            btn_pause.Enabled    = true;
            btn_stop.Enabled     = true;
            vsb_volumeL.Enabled  = true;
            vsb_volumeM.Enabled  = true;
            vsb_volumeR.Enabled  = true;
            trb_progress.Enabled = true;
            cb_controle.Enabled  = true;

            trb_progress.Maximum = (int)stream.TotalTime.TotalSeconds;
        }
Beispiel #14
0
        private static IEnumerable <PitchUnit> LoadAudioFile(string fileName, bool play)
        {
            using (var playerReader = new AudioFileReader(fileName))
                using (var player = new WaveOutEvent())
                {
                    if (play)
                    {
                        player.Init(playerReader);
                        player.Play();
                    }

                    var startTime = Environment.TickCount;

                    const int analysisUnit    = 4096;
                    const int pitchWindowSize = 1024;

                    using (var reader = new AudioFileReader(fileName))
                    {
                        var provider   = reader.ToSampleProvider().ToMono();
                        var sampleRate = provider.WaveFormat.SampleRate;
                        var samples    = new float[analysisUnit];

                        for (var unitIndex = 0; ; unitIndex++)
                        {
                            if (play)
                            {
                                var waitTime = (int)(startTime + unitIndex * analysisUnit * 1000.0 / sampleRate) - Environment.TickCount;
                                if (waitTime > 0)
                                {
                                    Thread.Sleep(waitTime);
                                }
                            }

                            for (var readSamples = 0; readSamples < samples.Length;)
                            {
                                var count = provider.Read(samples, readSamples, samples.Length - readSamples);
                                if (count == 0)
                                {
                                    yield break;
                                }
                                readSamples += count;
                            }

                            // 実効値を求める
                            var squared = 0.0;
                            for (var i = 0; i < samples.Length; i++)
                            {
                                squared += samples[i] * samples[i];
                            }
                            var rms = Math.Sqrt(squared / samples.Length);

                            // 512 ずつずらしながらピッチ検出
                            const int pitchOffsetDelta = 512;
                            var       f0s = new List <double>((analysisUnit - pitchOffsetDelta) / pitchOffsetDelta);
                            for (var offset = 0; offset <= analysisUnit - pitchWindowSize; offset += pitchOffsetDelta)
                            {
                                var f = McLeodPitchMethod.EstimateFundamentalFrequency(
                                    sampleRate,
                                    new ReadOnlySpan <float>(samples, offset, pitchWindowSize)
                                    );

                                if (f.HasValue)
                                {
                                    f0s.Add(f.Value);
                                }
                            }

                            if (f0s.Count == 0)
                            {
                                continue;
                            }

                            f0s.Sort();
                            var f0 = f0s[f0s.Count / 2]; // 中央値

                            var normalizedPitch = NormalizePitch(f0);
                            if (normalizedPitch.HasValue)
                            {
                                yield return(new PitchUnit(unitIndex, rms, normalizedPitch.Value));
                            }
                        }
                    }
                }
        }