private async Task Start(string audioFile) { await Task.Run(() => { try { lock (syncLock) { using (var audioFileReader = new AudioFileReader(audioFile)) { audioFileReader.Volume = settingsService.Settings.Volume * 0.01f; using (dso = new DirectSoundOut(settingsService.Settings.AudioDeviceId)) { dso.Init(audioFileReader); using (eventWaiter = new ManualResetEvent(false)) { dso.Play(); dso.PlaybackStopped += (sender, args) => eventWaiter.Set(); eventWaiter.WaitOne(); } } } } } catch (Exception) { } }); }
private void play_Click(object sender, EventArgs e) { if (playlist.SelectedItems.Count>0) { id = fn.IndexOf(playlist.SelectedItem.ToString()); if (waveOutDevice.PlaybackState.ToString() != "Paused") { t.Stop(); stp(); audioFileReader = new AudioFileReader(fp[id]); waveOutDevice = new WaveOut(); waveOutDevice.Init(audioFileReader); trackbar.Maximum = (int)audioFileReader.TotalTime.TotalSeconds + 1; //deb.Items.Add(audioFileReader.TotalTime.Seconds.ToString()); audioFileReader.Volume = (float)vol.Value / 100; waveOutDevice.Play(); t.Start(); } else { waveOutDevice.Play(); t.Start(); } } }
public static void Main(string[] argv) { ISampleProvider decoder = new AudioFileReader(FILE); SpectrumProvider spectrumProvider = new SpectrumProvider(decoder, 1024, HOP_SIZE, true); float[] spectrum = spectrumProvider.nextSpectrum(); float[] lastSpectrum = new float[spectrum.Length]; List<float> spectralFlux = new List<float>(); do { float flux = 0; for(int i = 0; i < spectrum.Length; i++) { float @value = (spectrum[i] - lastSpectrum[i]); flux += @value < 0 ? 0 : @value; } spectralFlux.Add(flux); System.Array.Copy(spectrum, 0, lastSpectrum, 0, spectrum.Length); } while((spectrum = spectrumProvider.nextSpectrum()) != null); Plot plot = new Plot("Hopping Spectral Flux", 1024, 512); plot.plot(spectralFlux, 1, Color.Red); new PlaybackVisualizer(plot, HOP_SIZE, FILE); }
public CachedSound(string audioFileName) { using (var audioFileReader = new AudioFileReader(audioFileName)) { WaveFormat = audioFileReader.WaveFormat; if (WaveFormat.SampleRate != 44100 || WaveFormat.Channels != 2) { using (var resampled = new ResamplerDmoStream(audioFileReader, WaveFormat.CreateIeeeFloatWaveFormat(44100, 2))) { var resampledSampleProvider = resampled.ToSampleProvider(); WaveFormat = resampledSampleProvider.WaveFormat; var wholeFile = new List<float>((int) (resampled.Length)); var readBuffer = new float[resampled.WaveFormat.SampleRate * resampled.WaveFormat.Channels]; int samplesRead; while ((samplesRead = resampledSampleProvider.Read(readBuffer, 0, readBuffer.Length)) > 0) { wholeFile.AddRange(readBuffer.Take(samplesRead)); } AudioData = wholeFile.ToArray(); } } else { var wholeFile = new List<float>((int) (audioFileReader.Length / 4)); var readBuffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels]; int samplesRead; while ((samplesRead = audioFileReader.Read(readBuffer, 0, readBuffer.Length)) > 0) { wholeFile.AddRange(readBuffer.Take(samplesRead)); } AudioData = wholeFile.ToArray(); } } }
long _length; // Number of bytes left to read /// <summary> /// Constructor /// </summary> /// <param name="start">in seconds</param> /// <param name="length">in seconds</param> public ExtractWaveProvider(AudioFileReader reader, float start, float length) { _reader = reader; // Position to start _reader.Position = _reader.WaveFormat.SecondsToBytes(start); // Number of bytes to read _length = _reader.WaveFormat.SecondsToBytes(length); }
private ISampleProvider BuildWavePartAudio(UWavePart part, UProject project) { AudioFileReader stream; try { stream = new AudioFileReader(part.FilePath); } catch { return null; } return new WaveToSampleProvider(stream); }
public void CanDownsampleAnMp3File() { string testFile = @"D:\Audio\Music\Coldplay\Mylo Xyloto\03 - Paradise.mp3"; if (!File.Exists(testFile)) Assert.Ignore(testFile); string outFile = @"d:\test22.wav"; using (var reader = new AudioFileReader(testFile)) { // downsample to 22kHz var resampler = new WdlResamplingSampleProvider(reader, 22050); var wp = new SampleToWaveProvider(resampler); using (var writer = new WaveFileWriter(outFile, wp.WaveFormat)) { byte[] b = new byte[wp.WaveFormat.AverageBytesPerSecond]; while (true) { int read = wp.Read(b, 0, b.Length); if (read > 0) writer.Write(b, 0, read); else break; } } //WaveFileWriter.CreateWaveFile(outFile, ); } }
/*public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename) * { * //rewind to beginning of stream * ms.Seek(0, SeekOrigin.Begin); * * using (var retMs = new MemoryStream()) * using (var rdr = new WaveFileReader(ms)) * using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90)) * { * rdr.CopyTo(wtr); * }*/ public void cnv(string sourceFilename, string targetFilename) { using (var reader = new NAudio.Wave.AudioFileReader(sourceFilename)) using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD)) { reader.CopyTo(writer); } }
public static void ConvertToMP3(string inFile, string outFile, int bitRate = 64) { using (var reader = new AudioFileReader(inFile)) { using (var writer = new LameMP3FileWriter(outFile, reader.WaveFormat, bitRate)) reader.CopyTo(writer); } }
protected virtual void Dispose(bool boolean) { if (boolean) { this.AudioReader.Dispose(); audio = null; Path = null; } }
private void playnhac() { IWavePlayer waveOutDevice; AudioFileReader audioFileReader; waveOutDevice = new WaveOut(); audioFileReader = new AudioFileReader("animal.mp3"); waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); }
public static void PlaySound(NotificationSound sound) { IWavePlayer waveOutDevice; AudioFileReader audioFileReader; waveOutDevice = new WaveOut(); audioFileReader = new AudioFileReader("resources/sounds/message.mp3"); waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); }
// Constructor public OnsetDetection(AudioFileReader pcm, int sampleWindow) { PCM = pcm; SampleSize = sampleWindow; spectrum = new float[sampleWindow / 2 + 1]; previousSpectrum = new float[spectrum.Length]; rectify = true; fluxes = new List<float>(); }
private void buttonSelectFile_Click(object sender, EventArgs e) { Cleanup(); var ofd = new OpenFileDialog(); ofd.Filter = "Audio files|*.wav;*.mp3"; if (ofd.ShowDialog() == DialogResult.OK) { this.reader = new AudioFileReader(ofd.FileName); } }
public void PlaySong() { // Instantiate audio player waveOutDevice = new WaveOut(); // Set MP3 to play audioFileReader = new AudioFileReader(GetSong()); // Init device and call play waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); }
public void LoadMp3File(string fileName) { if (aReader != null) aReader.Dispose(); aReader = new AudioFileReader(fileName); var sampleChannel = new SampleChannel(aReader, true); volumeMeter = new MeteringSampleProvider(sampleChannel); player.Init(volumeMeter); }
/// <summary> /// Begins the fade information. /// </summary> /// <param name="inputFile">The input file.</param> /// <param name="outputFile">The output file.</param> /// <param name="duration">The duration.</param> /// <returns> /// Path of changed file /// </returns> public static string BeginFadeIn(string inputFile, string outputFile, double duration) { using (var reader = new AudioFileReader(inputFile)) { var provider = new EffectsProvider(reader); provider.BeginFadeIn(duration * 1000); WaveFileWriter.CreateWaveFile16(outputFile, provider); } return outputFile; }
public override void Stage() { wavePlayer = new WaveOutEvent(); file = new AudioFileReader(_fileName); file.Volume = 1; wavePlayer.Init(file); wavePlayer.PlaybackStopped += new EventHandler<StoppedEventArgs>(PlaybackEnded); _currentStatus = Status.Staged; }
private void BeginPlayback(string filename) { Debug.Assert(this.wavePlayer == null); this.wavePlayer = CreateWavePlayer(); this.file = new AudioFileReader(filename); this.file.Volume = volumeSlider1.Volume; this.wavePlayer.Init(file); this.wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; this.wavePlayer.Play(); EnableButtons(true); timer1.Enabled = true; // timer for updating current time label }
public void Play() { var path = Path.Combine(@"E:\Dropbox\Music\Imagine Dragons\Night Visions", "01 - Radioactive.mp3"); var wavePlayer = new WaveOut(); var file = new AudioFileReader(path); file.Volume = 0.8f; wavePlayer.Init(file); ////wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; wavePlayer.Play(); Thread.Sleep(10000); }
private ISampleProvider CreateInputStream(string fileName) { this.audioFileReader = new AudioFileReader(fileName); var sampleChannel = new SampleChannel(audioFileReader, true); sampleChannel.PreVolumeMeter+= OnPreVolumeMeter; this.setVolumeDelegate = (vol) => sampleChannel.Volume = vol; var postVolumeMeter = new MeteringSampleProvider(sampleChannel); postVolumeMeter.StreamVolume += OnPostVolumeMeter; return postVolumeMeter; }
public static float[] BuildPeaks(UWavePart part, System.ComponentModel.BackgroundWorker worker) { const double peaksRate = 4000; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); float[] peaks; using (var stream = new AudioFileReader(part.FilePath)) { int channels = part.Channels; double peaksSamples = (int)((double)stream.Length / stream.WaveFormat.BlockAlign / stream.WaveFormat.SampleRate * peaksRate); peaks = new float[(int)(peaksSamples + 1) * channels]; double blocksPerPixel = stream.Length / stream.WaveFormat.BlockAlign / peaksSamples; var converted = new WaveToSampleProvider(stream); float[] buffer = new float[4096]; int readed; int readPos = 0; int peaksPos = 0; double bufferPos = 0; float lmax = 0, lmin = 0, rmax = 0, rmin = 0; while ((readed = converted.Read(buffer, 0, 4096)) != 0) { readPos += readed; for (int i = 0; i < readed; i += channels) { lmax = Math.Max(lmax, buffer[i]); lmin = Math.Min(lmin, buffer[i]); if (channels > 1) { rmax = Math.Max(rmax, buffer[i + 1]); rmin = Math.Min(rmin, buffer[i + 1]); } if (i > bufferPos) { lmax = -lmax; lmin = -lmin; rmax = -rmax; rmin = -rmin; // negate peaks to fipped waveform peaks[peaksPos * channels] = lmax == 0 ? lmin : lmin == 0 ? lmax : (lmin + lmax) / 2; peaks[peaksPos * channels + 1] = rmax == 0 ? rmin : rmin == 0 ? rmax : (rmin + rmax) / 2; peaksPos++; lmax = lmin = rmax = rmin = 0; bufferPos += blocksPerPixel * stream.WaveFormat.Channels; } } bufferPos -= readed; worker.ReportProgress((int)((double)readPos * sizeof(float) * 100 / stream.Length)); } } sw.Stop(); System.Diagnostics.Debug.WriteLine("Build peaks {0} ms", sw.Elapsed.TotalMilliseconds); return peaks; }
// Method for creating float array from given wav file public void wavToFloatArray(string path) { audio = new NAudio.Wave.AudioFileReader(path); NAudio.Wave.WaveFormat waveFormat = audio.WaveFormat; midLen += audio.Length; algo.set_fs(waveFormat.SampleRate); algo.defineStepAndLength(); originalWavSamples = new float[audio.Length / 4]; algo.setSamples(originalWavSamples.Length); audio.Read(originalWavSamples, 0, originalWavSamples.Length); audio.Close(); }
public string LoadSong() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "WAV|*.wav|MP3|*.mp3"; if (ofd.ShowDialog() == true) { FilePath = ofd.FileName; audioFileReader = new AudioFileReader(FilePath); return FilePath; } else { return String.Empty;} }
private void BeginPlayback(string filename) { Debug.Assert(this.wavePlayer == null); this.wavePlayer = new WaveOutEvent(); this.file = new AudioFileReader(filename); this.fadeInOut = new FadeInOutSampleProvider(file); this.file.Volume = volumeSlider1.Volume; this.wavePlayer.Init(new SampleToWaveProvider(fadeInOut)); this.wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; this.wavePlayer.Play(); EnableButtons(true); timer1.Enabled = true; // timer for updating current time label }
private void CleanUp() { if (this.file != null) { this.file.Dispose(); this.file = null; } if (this.wavePlayer != null) { this.wavePlayer.Dispose(); this.wavePlayer = null; } }
private void Cleanup() { if (asioOut != null) { asioOut.Dispose(); asioOut = null; } if (reader != null) { reader.Dispose(); reader = null; } }
/// <summary> /// Disposes of all resources contained in BGMusic. Call this method at the /// end of the Game's life. /// </summary> public static void dispose() { if (file != null) { file.Dispose(); file = null; } if (wavePlayer != null) { wavePlayer.Dispose(); wavePlayer = null; } fadeInOut = null; }
public IWavePlayer PlayKillStreak(string sfxName, string ext = "wav") { KillStreakDevice = KillStreakDevice ?? new WaveOutEvent(); var path = SFXPath + sfxName + "." + ext; Wait(250); AudioFileReader audioFileReader = new AudioFileReader(path); audioFileReader.Volume = 0.6f * Volume; KillStreakDevice.Stop(); KillStreakDevice.Init(audioFileReader); KillStreakDevice.Play(); return KillStreakDevice; }
public static void Main(string[] argv) { AudioDevice device = new AudioDevice(); ISampleProvider reader = new AudioFileReader("samples/sample.wav"); float[] samples = new float[1024]; while(reader.Read(samples, 0, samples.Length) > 0) { device.WriteSamples(samples); } System.Threading.Thread.Sleep(10000); device.Dispose(); }
public AudioDevice(string fileName) : this() { ISampleProvider sampleProvider = new AudioFileReader(fileName); this.fileWaveStream = (WaveStream) sampleProvider; // create sample channel SampleToWaveProvider waveProvider = new SampleToWaveProvider(sampleProvider); this.sampleChannel = new SampleChannel(waveProvider, true); this.sampleChannel.PreVolumeMeter += OnPreVolumeMeter; // play //IWavePlayer waveOut = new WaveOut(); //waveOut.Init(waveProvider); //waveOut.Play(); }
// Plays audio track public void Play(string FileName) { Console.Out.WriteLine("FileName is: " + FileName); reader = new NAudio.Wave.AudioFileReader(FileName); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(reader)); if (firstTime == true) { SetVolume((float).5); firstTime = false; } output.Play(); Program.MainForm.StartTimer(); }
// Stops music playback public void Stop() { if (output != null) { if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) { output.Stop(); } } if (reader != null) { reader.Dispose(); reader = null; } }
private static void WmaToMp3(XConvertJob param) { var targetFilename = string.IsNullOrEmpty(param.AlternativeOutputPath) ? param.SourceFileName.GenerateOutPutPath(XFileType.Mp3) : param.AlternativeOutputPath; if (param.SourceData != null) { File.WriteAllBytes(param.SourceFileName, param.SourceData); } using (var reader = new NAudio.Wave.AudioFileReader(param.SourceFileName)) using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD)) { reader.CopyTo(writer); } param.ResulFileName = targetFilename; }
protected virtual void LoadAudio() { if ((Path.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) || (Path.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))) { if (audio != null) { audio.Dispose(); } audio = new NAudio.Wave.AudioFileReader(Path); output.Init(audio); } else { throw new FileTypeException("File type must be .mp3 or .wav"); } }
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { AudioFileReader wave = null; WaveOut outputSound = null; string x = ""; if (treeView1.SelectedNode.Parent != null) { if (treeView1.SelectedNode.Parent.Index == 1) { SampleDef sd = seq.samples[treeView1.SelectedNode.Index]; propertyGrid1.SelectedObject = sd; x = seq.path + "\\" + seq.name + "\\" + sd.Tag + (Howl.sampledict.ContainsKey(sd.SampleID) ? "_" + Howl.sampledict[sd.SampleID] : "") + ".wav"; } if (treeView1.SelectedNode.Parent.Index == 0) { SampleDefReverb sd = seq.samplesReverb[treeView1.SelectedNode.Index]; propertyGrid1.SelectedObject = sd; x = seq.path + "\\" + seq.name + "\\" + sd.Tag + (Howl.sampledict.ContainsKey(sd.SampleID) ? "_" + Howl.sampledict[sd.SampleID] : "") + ".wav"; } if (File.Exists(x)) { try { wave = new NAudio.Wave.AudioFileReader(x); outputSound = new WaveOut(); outputSound.Init(wave); outputSound.Play(); } catch (Exception ex) { textBox1.Text = ex.Message; } } } else { propertyGrid1.SelectedObject = null; } }
public List <float> ReadFromMP3() { string filePath; if (choice == 0) { filePath = ChooseFile(); } else { filePath = @"out.mp3"; } List <float> allSamples = new List <float>(); float[] samples = new float[256]; AudioFileReader sampleProvider = new NAudio.Wave.AudioFileReader(filePath); int channels = sampleProvider.WaveFormat.Channels; while (sampleProvider.Read(samples, 0, samples.Length) > 0) { if (channels == 2) { for (int i = 0; i < samples.Length; i = i + 2) { allSamples.Add((samples[i] + samples[i + 1]) / 2); } } else { for (int i = 0; i < samples.Length; i++) { allSamples.Add(samples[i]); } } } return(allSamples); }
static void Main(string[] args) { string mp3FilesDir = Directory.GetCurrentDirectory(); if (args.Length > 0) { mp3FilesDir = args.First(); } var waveOutDevice = new WaveOut(); var idToFile = Directory.GetFiles(mp3FilesDir, "*.mp3", SearchOption.AllDirectories).ToDictionary(k => int.Parse(Regex.Match(Path.GetFileName(k), @"^\d+").Value)); while (true) { Console.WriteLine("Wprowadz numer nagrania"); var trackId = int.Parse(Console.ReadLine()); using (var audioFileReader = new AudioFileReader(idToFile[trackId])) { waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); Console.ReadLine(); } } }
public static void Main(string[] argv) { ISampleProvider decoder = new AudioFileReader(FILE); FFT fft = new FFT(1024, 44100); fft.Window(FFT.HAMMING); float[] samples = new float[1024]; float[] spectrum = new float[1024 / 2 + 1]; float[] lastSpectrum = new float[1024 / 2 + 1]; List<float> spectralFlux = new List<float>(); while(decoder.Read(samples, 0, samples.Length) > 0) { fft.Forward(samples); System.Array.Copy(spectrum, 0, lastSpectrum, 0, spectrum.Length); System.Array.Copy(fft.GetSpectrum(), 0, spectrum, 0, spectrum.Length); float flux = 0; for(int i = 0; i < spectrum.Length; i++) { float @value = (spectrum[i] - lastSpectrum[i]); flux += @value < 0 ? 0 : @value; } spectralFlux.Add(flux); } Plot plot = new Plot("Hamming Spectral Flux", 1024, 512); plot.plot(spectralFlux, 1, Color.Red); new PlaybackVisualizer(plot, 1024, FILE); }