public Init ( IWaveProvider waveProvider ) : void | ||
waveProvider | IWaveProvider | The waveprovider to be played |
return | void |
static void Main(string[] args) { IWavePlayer waveOutDevice; WaveStream mainOutputStream; string fileName = @"C:\Users\Yuval\Sources\PracticeSharpProject\Audio\Ringtone 01.wma"; Console.WriteLine("Initiailizing NAudio"); try { waveOutDevice = new DirectSoundOut(50); } catch (Exception driverCreateException) { Console.WriteLine(String.Format("{0}", driverCreateException.Message)); return; } mainOutputStream = CreateInputStream(fileName); try { waveOutDevice.Init(mainOutputStream); } catch (Exception initException) { Console.WriteLine(String.Format("{0}", initException.Message), "Error Initializing Output"); return; } Console.WriteLine("NAudio Total Time: " + (mainOutputStream as WaveChannel32).TotalTime); Console.WriteLine("Playing WMA.."); waveOutDevice.Volume = 1.0f; waveOutDevice.Play(); Console.ReadKey(); Console.WriteLine("Seeking to new time: 00:00:20.."); (mainOutputStream as WaveChannel32).CurrentTime = new TimeSpan(0, 0, 20); Console.ReadKey(); Console.WriteLine("Hit key to stop.."); waveOutDevice.Stop(); Console.WriteLine("Finished.."); mainOutputStream.Dispose(); waveOutDevice.Dispose(); Console.WriteLine("Press key to exit..."); Console.ReadKey(); }
private void AudioPlayerWorkNAudio() { NAudio.Wave.DirectSoundOut output = new NAudio.Wave.DirectSoundOut(); output.PlaybackStopped += ResetAudio; AudioStream audioStream = new AudioStream(audioResetTime, false); ActiveAudioStream = audioStream; while (!Stop) { audioStream = ActiveAudioStream; AudioWaveStream audioWaveStream = new AudioWaveStream(audioStream); output.Init(new NAudio.Wave.WaveChannel32(audioWaveStream) { PadWithZeroes = false }); try { output.Play(); } catch { output.Stop(); } while (audioStream == ActiveAudioStream) { System.Threading.Thread.Sleep(1); } output.Stop(); } }
public static Boolean SpeakerTest(int channel) { String wavFile = ""; wavFile = System.IO.Path.GetDirectoryName(Application.ExecutablePath); NAudio.Wave.WaveFileReader wave = null; NAudio.Wave.DirectSoundOut output = null; if (channel == 0) { wavFile += "\\440Hz_sine_left.wav"; } else { wavFile += "\\440Hz_sine_right.wav"; } wave = new NAudio.Wave.WaveFileReader(wavFile); output = new NAudio.Wave.DirectSoundOut(); output.Init(new WaveChannel32(wave)); output.Play(); return(false); }
private void playSound(String type, String dir) { DisposeWave(); if (type.Equals("LETTER")) { wave = new NAudio.Wave.WaveFileReader(dir); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); } else if (type.Equals("WON")) { wave = new NAudio.Wave.WaveFileReader(dir); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); } else if (type.Equals("LOSE")) { wave = new NAudio.Wave.WaveFileReader(dir); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); } }
public DirectSoundPlayer(INetworkChatCodec c) : base(c) { waveProvider = new BufferedWaveProvider(codec.RecordFormat); wavePlayer = new DirectSoundOut(); wavePlayer.Init(waveProvider); }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { DisposeWave(); string query1 = "Select Track.track_path from Track where Track_name = '" + listBox1.SelectedItem.ToString() + "'"; SqlCommand cmd1 = new SqlCommand(query1, con); SqlDataReader dbr1; dbr1 = cmd1.ExecuteReader(); string sname = null; while (dbr1.Read()) { sname = (string)dbr1["track_path"];; // is coming from database } dbr1.Close(); pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(sname)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); }
// Maethod to initialize thread for opening the wav file public void initPlay() { DisposeWave(); waveReader = new NAudio.Wave.WaveFileReader(wavOpenName); waveOut = new NAudio.Wave.DirectSoundOut(); waveOut.Init(new NAudio.Wave.WaveChannel32(waveReader)); }
private void Aleatorio() { int i = 0; for (i = 0; i < TreeMostra.Nodes.Count; i++) { //Só pra contar quantos nodes tem para pegar o index dele e fazer o aleatorio } Random rdn = new Random(); int strNumeroaleatorio; strNumeroaleatorio = rdn.Next(0, i - 1);// gera o numero aleatorio de 0 até o tamanho do treeview if (output != null) { output.Stop(); } NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.Nodes[strNumeroaleatorio].Text));//TreeMostra.SelectedNode.Text stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); BtnPause.Enabled = true; BtnPlaySelec.Enabled = false; BtnStop.Enabled = true; BtnProximo.Enabled = true; }
private void ProximaMusica() { try { if (output != null) { output.Stop(); } if (musicatoc == TreeMostra.Nodes.Count - 1) { musicatoc = 0; } else { musicatoc++; } NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.Nodes[musicatoc].Text));//TreeMostra.SelectedNode.Text stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); BtnPause.Enabled = true; BtnPlaySelec.Enabled = false; BtnStop.Enabled = true; BtnProximo.Enabled = true; } catch { MessageBox.Show("Você tem que selecionar uma música primeiro para depois tocar a proxima "); } }
private void BtnNext_Click(object sender, EventArgs e) { if (output == null) { MessageBox.Show("No more songs in playlist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (ListBox.SelectedIndex != ListBox.Items.Count - 1) { //counter for get selected index in listbox int count = 0; ListBox.SetSelected(count + 1, true); int nextIndex = ListBox.SelectedIndex + 1; DisposeWave(); OpenFileDialog forwardSong = new OpenFileDialog(); //getting the string of the next song string nextSong = ListBox.Items[nextIndex].ToString(); NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(forwardSong.FileName)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); LblTest.Text = path[0]; LblNowPlaying.Text = files[0]; //play output output.Play(); } }
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) { } }); }
public Music(string path) { DisposeMusic(); WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(path)); stream = new BlockAlignReductionStream(pcm); output = new DirectSoundOut(); output.Init(stream); }
public ScoreMusicPlayer() { _syncObject = new object(); _waveStream = new WaveMixerStream32(); _soundPlayer = new AudioOut(); _soundPlayer.Init(_waveStream); _channels = new Dictionary <WaveStream, WaveChannel32>(); }
private void playButton_Click(object sender, EventArgs e) { waveReader = new NAudio.Wave.WaveFileReader(outputFilePath); output = new NAudio.Wave.DirectSoundOut(100); output.Init(new NAudio.Wave.WaveChannel32(waveReader)); output.Play(); playButton.Enabled = false; }
public void PlayMusic(AudioReference reference) { //@"C:\Program Files\Maxis\The Sims Online\TSOClient\music\stations\countryd\cntryd1_5df26ad0.mp3" var file = Load(reference.FilePath); ; //var file = Load(@"C:\Program Files\Maxis\The Sims Online\TSOClient\sounddata\tvstations\tv_comedy_cartoon\tv_c1_12.xa"); ; var output = new DirectSoundOut(); output.Init(file); output.Play(); }
public static void PreviousChannelWhoosh() { _wave = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(@"..\..\Resources\Sounds\woosh_prev.mp3")); _stream = new BlockAlignReductionStream(_wave); _output = new DirectSoundOut(); _output.Init(_stream); _output.Play(); }
public void playSound(string file) { NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(file)); BlockAlignReductionStream stream = new NAudio.Wave.BlockAlignReductionStream(pcm); DirectSoundOut output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); Thread.Sleep(((int)new AudioFileReader(file).TotalTime.TotalMilliseconds) + soundDelay); }
//this method sets up the sourcestream, the waveout and the buffer where our sourcestream data will be sent. //the devices are set up either as chosen in the settings panel or as the first(and usually only) availuable devices as default private void InitializeSound() { sourceStream = new NAudio.Wave.WaveIn(); sourceStream.DeviceNumber = setting.deviceNumber; // input device number = 0 as default to prevent error. thats also usually the mic when using my PC. need to ensure its the same for my laptop for presentation sourceStream.WaveFormat = setting.format; sourceStream.DataAvailable += waveIn_DataAvailable; // calls method to control what happens to data as it comes in waveOut = new NAudio.Wave.DirectSoundOut(); //creates wave output device buffer = new BufferedWaveProvider(sourceStream.WaveFormat); //initialises buffer in the same format as the wavestream waveOut.Init(buffer); //connects the buffer with the output device }
private void BtnOpenFiles_Click(object sender, EventArgs e) { //make sure listbox is visible to the user ListBox.Visible = true; //when open file loads set login page to not visible LblUsernameLogin.Visible = false; LblPasswordLogin.Visible = false; TxtUsername.Visible = false; TxtPassword.Visible = false; CBoxSavePassword.Visible = false; BtnLoginUserPass.Visible = false; BtnLogin.Text = "Login"; OpenFileDialog songChoice = new OpenFileDialog(); //filter only mp3 filetypes in files songChoice.Filter = "Mp3 File(*.mp3)|*.mp3"; //select more than one track songChoice.Multiselect = true; if (songChoice.ShowDialog() == DialogResult.OK) { files = songChoice.SafeFileNames; path = songChoice.FileNames; //adding items to list for (int index = 0; index < files.Length; index++) { ListBox.Items.Add(files[index]); } //highlights current song playing ListBox.SetSelected(0, true); //dispose function to get rid of the current song in WaveStream NAudio DisposeWave(); NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(songChoice.FileName)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); LblTest.Text = path[0]; LblNowPlaying.Text = files[0]; //play song output.Play(); //hide the play button BtnPlay.Visible = false; BtnPause.Visible = true; } }
static void Main(string[] args) { IWavePlayer waveOutDevice; WaveStream mainOutputStream; string fileName = @"..\..\Audio\test.ogg"; Console.WriteLine("Initiailizing NAudio"); try { waveOutDevice = new DirectSoundOut(50); } catch (Exception driverCreateException) { Console.WriteLine(String.Format("{0}", driverCreateException.Message)); return; } mainOutputStream = CreateInputStream(fileName); try { waveOutDevice.Init(mainOutputStream); } catch (Exception initException) { Console.WriteLine(String.Format("{0}", initException.Message), "Error Initializing Output"); return; } Console.WriteLine("NAudio Total Time: " + (mainOutputStream as WaveChannel32).TotalTime); Console.WriteLine("Playing Ogg Vorbis.."); waveOutDevice.Volume = 1.0f; waveOutDevice.Play(); Console.ReadKey(); Console.WriteLine("Seeking to new time: 00:01:00.."); (mainOutputStream as WaveChannel32).CurrentTime = new TimeSpan(0, 1, 0); Console.ReadKey(); waveOutDevice.Stop(); Console.WriteLine("Finished.."); mainOutputStream.Dispose(); waveOutDevice.Dispose(); Console.WriteLine("Press key to exit..."); Console.ReadKey(); }
public void Open() { _finished = false; _circularBuffer = new CircularSampleBuffer(BufferSize * BufferCount); _context = new DirectSoundOut(100); _context.Init(this); OnReadyChanged(true); }
private void repeatBtn_Click(object sender, EventArgs e) { String filename = "Class" + LoginForm.classSec + "_kidWordAudio/" + levels[curPos] + ";.wav"; DisposeWave(); wave = new NAudio.Wave.WaveFileReader(filename); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); }
private App() { var waveOut = new DirectSoundOut(60); var osc = new Oscillator(44100, Math.Sin); var controller = LeapController.GetController(); var listener = controller.Listener; listener.Frames.Select(f => (f.Hands.Count > 0) ? f.Hands[0].PalmPosition.y : 0.0).Subscribe(osc.Frequency); waveOut.Init(new StreamProvider(osc)); 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(); }
public Synth() { MidiControl midiControl = new MidiControl(midiDeviceNumber); midiControl.startDeviceListener(); midiControl.MidiKeyPressed += MidiControl_MidiKeyPressed; waveFormProvider.SetWaveFormat(44100, 1); // 44.1 kHz mono waveFormProvider.setAmplitude(0.1f); waveFormProvider.setFrequency(500); waveFormProvider.setWaveForm(WaveFormProvider.WaveForm.Saw); waveOut = new DirectSoundOut(50); waveOut.Init(waveFormProvider); }
public void play_sound(string file) { NAudio.Wave.DirectSoundOut waveOut = new NAudio.Wave.DirectSoundOut(); NAudio.Wave.WaveFileReader wfr = new NAudio.Wave.WaveFileReader(file); NAudio.Wave.WaveOut wOut = new NAudio.Wave.WaveOut(); wOut.DeviceNumber = 0; wOut.Init(wfr); wOut.Play(); waveOut.Init(wfr); waveOut.Play(); }
private void CreateOutput() { var vwp = new VolumeWaveProvider16(_buffer); var dso = new DirectSoundOut(70); vwp.Volume = _currentVolume; Debug.WriteLine("Now playing at {0}% volume", dso.Volume); dso.Init(vwp); dso.Play(); vwp.Volume = _currentVolume; _currentOut = dso; _volumeWaveProvider = vwp; }
public MyItemControl(Word word) { InitializeComponent(); _word = word; Picture = null;// con.ByteToWPFImage(word.Picture); waveReader = new WaveFileReader(con.byteArrayToStream(_word.Sound)); SoundLength = waveReader.TotalTime; wc = new WaveChannel32(waveReader); audioOutput = new DirectSoundOut(); audioOutput.Init(wc); track.ValueChangedManually += track_PositionChangedManually; myTrack.ValueChangedManually += track_PositionChangedManually; myTrack.MouseLeftButtonDown += track_MouseLeftButtonDown; myTrack.Loaded += track_Loaded; }
public void SoundOutput(string header, bool IsWin8) { /** * * 출력할 소리가 wav인지 mp3인지 비프음인지 채크합니다. * windows8 이상의 경우에는 비프음보다 윈도우8 기본 알림음이 더 알맞다고 생각하기에 IsWin8이 True면 아무 소리도 내보내지 않습니다. * **/ DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지 try { var Audiofile = GetRandomSound(header); if (!IsWin8 && Audiofile == null) { SystemSounds.Beep.Play(); //FileCheck에서 음소거 채크를 하고 음소거상태이거나 파일이 없는경우 비프음 출력 return; } else if (IsWin8 && Audiofile == null) return; //위와 동일한 조건이지만 윈도우8인경우는 이 소스에서는 아무 소리도 내보내지않음. float Volume = Settings.Current.CustomSoundVolume > 0 ? (float)Settings.Current.CustomSoundVolume / 100 : 0; if (Path.GetExtension(Audiofile).ToLower() == ".wav") { WaveStream pcm = new WaveChannel32(new WaveFileReader(Audiofile), Volume, 0); BlockStream = new BlockAlignReductionStream(pcm); } else if (Path.GetExtension(Audiofile).ToLower() == ".mp3") { WaveStream pcm = new WaveChannel32(new Mp3FileReader(Audiofile), Volume, 0); BlockStream = new BlockAlignReductionStream(pcm); } else return; SoundOut = new DirectSoundOut(); SoundOut.Init(BlockStream); SoundOut.Play(); } catch (Exception ex) { StatusService.Current.Notify("Unable to play sound notification: " + ex.Message); } }
public void editorSesDinlemeBaslat() { int deviceNumber = sesCihazComboBox.SelectedIndex; sourceStream = new NAudio.Wave.WaveIn(); sourceStream.DeviceNumber = deviceNumber; sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(48000, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels); NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream); waveOut = new NAudio.Wave.DirectSoundOut(); waveOut.Init(waveIn); sourceStream.StartRecording(); waveOut.Play(); onbellekSayiLabel.Text = "Kullanılacak Önbellek Sayısı: " + sourceStream.NumberOfBuffers; }
System.Windows.Forms.Timer timerStat; //таймер для статистики #endregion Fields #region Constructors //конструктор по умолчанию public Form1() { InitializeComponent(); //инициализируем интерфейс comboBoxBaud.SelectedIndex = 0; //значения combobox по умолчанию comboBoxFlow.SelectedIndex = 0; disconnectToolStripMenuItem.Enabled = false; //переключаем интерфейс stopToolStripMenuItem.Enabled = false; startToolStripMenuItem.Enabled = false; ZigUsb = new SerialPort(); //инициализируем объект порта voiceCodec = new VoiceOverZigbee.Codec.ALawChatCodec(); //инициализируем объект кодека output = new DirectSoundOut(); //инициализируем объект для считывания голоса bufferStream = new BufferedWaveProvider(voiceCodec.RecordFormat); //задаем формат буферу воспроизведения голоса, он соответствует формату кодека output.Init(bufferStream); //задаем соответствие буфера - объекту воспроизведения listenThread = new ListeningThread(new ThreadStart(Listening)); //инициализируем поток делегатом с функцией на выполнение в качестве аргумента connected = false; //флаг о передачи данных flagThread = false; //флаг о потоке }
private void setButtons(object sender, EventArgs e) { if (isPlaying == true) { output.Stop(); } string s = (sender as Button).Text; WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(songsAdded[findClickedSong(s)].path)); stream = new BlockAlignReductionStream(pcm); output = new DirectSoundOut(); output.Init(stream); output.Play(); if (!isPlaying) { isPlaying = true; } }
//Plays the concatenated phonics words, this is for teacher's to test if it sounds good or not ! private void testWordBtn_Click(object sender, EventArgs e) { if (wordLabel.Text.Length > 0) { String word = wordLabel.Text; String filename = @"PhonicsWord_Audio\" + word + ".wav"; DisposeWave(); wave = new NAudio.Wave.WaveFileReader(filename); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); } else { MessageBox.Show("Word isn't created yet !"); } }
private void button1_Click(object sender, EventArgs e) { /* * A saját hangomat adja vissza a default mikrofonból */ int deviceNumber = 0; source = new NAudio.Wave.WaveIn(); source.DeviceNumber = deviceNumber; source.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels); NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(source); waveout = new NAudio.Wave.DirectSoundOut(); waveout.Init(waveIn); source.StartRecording(); waveout.Play(); }
public int EnqueueSamples(int channels, int rate, byte[] samples, int frames) { if (bufferedWaveProvider == null) { bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(rate, channels)); volumeWaveProvider = new VolumeWaveProvider16(bufferedWaveProvider) {Volume = volumeControl.CurrentVolume}; //Output = new WasapiOut(AudioClientShareMode.Shared, false, 0); Output = new DirectSoundOut(70); Output.Init(volumeWaveProvider); Output.Play(); } int space = bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes; if (space > samples.Length) { bufferedWaveProvider.AddSamples(samples, 0, samples.Length); return frames; } return 0; }
// Простой обработчик данных - просто берет и проигрывает. private void Button_Click(object sender, RoutedEventArgs e) { var ofd = new OpenFileDialog(); Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".wav"; dlg.Filter = "WAV files (.wav)|*.wav"; Nullable <bool> result = dlg.ShowDialog(); if (dlg.ShowDialog() == false) { return; } wave = new NAudio.Wave.WaveFileReader(dlg.FileName); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); }
//otwieranie pliku wav private void openBtn_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = " Wave File (*.wav)|*.wav;"; if (open.ShowDialog() != DialogResult.OK) { return; } DisposeWave(); NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName)); output = new NAudio.Wave.DirectSoundOut(); output.Init(wave); output.Play(); pauseBtn.Enabled = true; }
public void SoundOutput(string header, bool IsWin8) { try { DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지 if (!Directory.Exists(Path.Combine(Main_folder, "Sounds"))) Directory.CreateDirectory(Path.Combine(Main_folder, "Sounds")); List<string> FileList = Directory.GetFiles(Path.Combine(Main_folder, "Sounds"), "*.wav", SearchOption.AllDirectories) .Concat(Directory.GetFiles(Path.Combine(Main_folder, "Sounds"), "*.mp3", SearchOption.AllDirectories)).ToList();//mp3와 wav를 검색하여 추가 string Audiofile = string.Empty; if (FileList.Count > 0) { Random Rnd = new Random(); Audiofile = FileList[Rnd.Next(0, FileList.Count)]; float Volume = AppSettings.Default.CustomSoundVolume > 0 ? (float)AppSettings.Default.CustomSoundVolume / 100 : 0; if (Path.GetExtension(Audiofile).ToLower() == ".wav")//wav인지 채크 { WaveStream pcm = new WaveChannel32(new WaveFileReader(Audiofile), Volume, 0); BlockStream = new BlockAlignReductionStream(pcm); } else if (Path.GetExtension(Audiofile).ToLower() == ".mp3")//mp3인 경우 { WaveStream pcm = new WaveChannel32(new Mp3FileReader(Audiofile), Volume, 0); BlockStream = new BlockAlignReductionStream(pcm); } SoundOut = new DirectSoundOut(); SoundOut.Init(BlockStream); SoundOut.Play(); } else { System.Media.SystemSounds.Beep.Play(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); System.Media.SystemSounds.Beep.Play(); } }
static void Main(string[] args) { var quit = new ManualResetEvent(false); Console.CancelKeyPress += (s, a) => { quit.Set(); a.Cancel = true; }; var device = new DirectSoundOut(); var audio = new AudioFileReader("doowackadoo.mp3"); device.Init(audio); device.Play(); Console.WriteLine("Playing doowackadoo; Ctrl+C to quit"); quit.WaitOne(); if(device != null) device.Stop(); if(audio != null) audio.Dispose(); if(device != null) device.Dispose(); }
private void PlayMusicaSelected() { try {// ve a musica selecionada e pega o index dela que automaticamente é a posiçao dela na lista e toca ela. NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(TreeMostra.SelectedNode.Text)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); BtnPause.Enabled = true; BtnPlaySelec.Enabled = false; BtnStop.Enabled = true; BtnAleatório.Enabled = true; BtnProximo.Enabled = true; musicatoc = TreeMostra.SelectedNode.Index; } catch { MessageBox.Show("Não tem nenhuma música selecionada"); } }
private void button2_Click(object sender, EventArgs e) { if (SourceList.SelectedItems.Count == 0) { return; } int deviceNumber = SourceList.SelectedItems[0].Index; sourceStream = new NAudio.Wave.WaveIn(); sourceStream.DeviceNumber = deviceNumber; sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels); NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream); waveOut = new NAudio.Wave.DirectSoundOut(); waveOut.Init(waveIn); sourceStream.StartRecording(); waveOut.Play(); }
private static int Play(BasePlayer player) { var a = new NAudio.Wave.DirectSoundOut(); var wp = new SequenceWaveProviderAdapter(player); a.Init(wp); a.Play(); { var aType = a.GetType(); var field = aType.GetField("notifyThread", BindingFlags.Instance | BindingFlags.NonPublic); var thread = (Thread)field.GetValue(a); thread.Name = "Audio playback Thread"; thread.Priority = ThreadPriority.Highest; } Thread.Sleep(10000 * 1000); a.Stop(); return(ERR_OK); }
public void MP3PlayFile(string fileName) { this.fileName = fileName; if (fileName.EndsWith(".mp3")) { NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(fileName)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); } else if (fileName.EndsWith(".wav")) { NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(fileName)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); } else { throw new InvalidOperationException("Not a correct audio file type."); } output = new NAudio.Wave.DirectSoundOut(); //output = new WaveOut(); output.Init(stream); output.Play(); //output.Volume = 1.0f; }
/// <summary> /// Create a new audio interface /// </summary> /// <param name="samplingFrequency">The sampling rate assumed, in Hz</param> /// <param name="blockSize">The block size used to calculate the spectrum of the signal, must be a power of two</param> public AudioProcessor(int samplingFrequency = 8000, int blockSize = 128) { //Initialise collections and fields Samples = new ObservableCollection<short>(); Spectrum = new ObservableCollection<float[]>(); SamplingFrequency = samplingFrequency; Samples.CollectionChanged += new NotifyCollectionChangedEventHandler(Samples_CollectionChanged); OnPropertyChanged("Samples"); //Check and initialise block size if (!isPowerOfTwo(blockSize)) { throw new ArgumentException("BlockSize must be a power of two for the FFT"); } BlockSize = blockSize; //Calculate the FFT frequencies SpectrumFrequencies = new ObservableCollection<float>(); for (int i = 0; i < (BlockSize / 2); i++) { SpectrumFrequencies.Add((float)((i / (float)BlockSize) * SamplingFrequency)); } //Initialise the sound player player = new DirectSoundOut(); var format = new WaveFormat(SamplingFrequency, 8, 1); provider = new ArrayWaveProvider(Samples, format); player.Init(provider); player.PlaybackStopped += new EventHandler<StoppedEventArgs>(player_PlaybackStopped); //Initialise the property changed timer notifyProperties = new DispatcherTimer(); notifyProperties.Interval = new TimeSpan(0, 0, 0, 0, 10); notifyProperties.Tick += new EventHandler(notifyProperties_Tick); }
public void Play() { var file = Path.Combine(BasicTeraData.Instance.ResourceDirectory, "sound/", File); try { var outputStream = new MediaFoundationReader(file); var volumeStream = new WaveChannel32(outputStream); volumeStream.Volume = Volume; //Create WaveOutEvent since it works in Background and UI Threads var player = new DirectSoundOut(); //Init Player with Configured Volume Stream player.Init(volumeStream); player.Play(); var timer = new Timer((obj) => { player.Stop(); player.Dispose(); volumeStream.Dispose(); outputStream.Dispose(); outputStream = null; player = null; volumeStream = null; }, null, Duration, Timeout.Infinite); } catch (Exception e) { // Get stack trace for the exception with source file information var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); BasicTeraData.LogError("Sound ERROR test" + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException + Environment.NewLine + e + Environment.NewLine + "filename:" + file + Environment.NewLine + "line:" + line, false, true); } }
private void timer1_Tick(object sender, EventArgs e) { seconds = seconds - 1; if (seconds == 0) { clearPanel(); stopProcess(); gameOverLabel.Visible = true; restartLabel.Visible = true; gameOverLabel.Text = "GAME OVER !"; restartLabel.Text = "PRESS RESTART\nTO TRY AGAIN !"; soundPicBox.Visible = false; String file = @"C:\Pres_Proto\V2\MetroFrameworkDLLExample\airhorn.wav"; wave = new NAudio.Wave.WaveFileReader(file); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); MessageBox.Show("TIME'S UP !"); MessageBox.Show("Total score: " + points); } timerLabel.Text = Convert.ToString(seconds); }
//Организовали зацикливание помех private void Looper() { WaveFileReader wfr = new WaveFileReader(Properties.Resources.background); WaveChannel32 wc = new WaveChannel32(wfr, vol, 0); DirectSoundOut wfo = new DirectSoundOut(); wfo.Init(wc); wfo.Play(); }
private void EncodeButton_Click(object sender, EventArgs e) { vol = VolumeTrk.Value*float.Parse((0.01).ToString()); text = MainRTextBox.Text; Stream str; SoundPlayer sp = new SoundPlayer(); WaveFileReader wfr = new WaveFileReader(Properties.Resources.background); WaveChannel32 wc = new WaveChannel32(wfr,vol,0); DirectSoundOut wfo = new DirectSoundOut(); wfo.Init(wc); wfo.Play(); System.Timers.Timer glc = new System.Timers.Timer(Int32.Parse(IntervalBox.Text)); if (IntervalBox.Enabled) { glc.Start(); glc.Elapsed += new ElapsedEventHandler(glctick); } System.Timers.Timer la = new System.Timers.Timer(2000); la.Elapsed += new ElapsedEventHandler(latick); la.Start(); foreach (char a in text.ToLower()) { //Ищем совпадения по буквам и произносим символ if (english.IndexOf(a) != -1) { switch (a) { case 'a': str = Properties.Resources.a; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(474 + Int32.Parse(TextSpeed.Text)); break; case 'b': str = Properties.Resources.b; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(504 + Int32.Parse(TextSpeed.Text)); break; case 'c': str = Properties.Resources.c; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(517 + Int32.Parse(TextSpeed.Text)); break; case 'd': str = Properties.Resources.d; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(478 + Int32.Parse(TextSpeed.Text)); break; case 'e': str = Properties.Resources.e; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(388 + Int32.Parse(TextSpeed.Text)); break; case 'f': str = Properties.Resources.f; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(623 + Int32.Parse(TextSpeed.Text)); break; case 'g': str = Properties.Resources.g; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(359 + Int32.Parse(TextSpeed.Text)); break; case 'h': str = Properties.Resources.h; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(571 + Int32.Parse(TextSpeed.Text)); break; case 'i': str = Properties.Resources.i; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(432 + Int32.Parse(TextSpeed.Text)); break; case 'j': str = Properties.Resources.j; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(548 + Int32.Parse(TextSpeed.Text)); break; case 'k': str = Properties.Resources.k; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(457 + Int32.Parse(TextSpeed.Text)); break; case 'l': str = Properties.Resources.l; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(434 + Int32.Parse(TextSpeed.Text)); break; case 'm': str = Properties.Resources.m; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(511 + Int32.Parse(TextSpeed.Text)); break; case 'n': str = Properties.Resources.n; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(614 + Int32.Parse(TextSpeed.Text)); break; case 'o': str = Properties.Resources.o; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(460 + Int32.Parse(TextSpeed.Text)); break; case 'p': str = Properties.Resources.p; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(420 + Int32.Parse(TextSpeed.Text)); break; case 'q': str = Properties.Resources.q; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(500 + Int32.Parse(TextSpeed.Text)); break; case 'r': str = Properties.Resources.r; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(632 + Int32.Parse(TextSpeed.Text)); break; case 's': str = Properties.Resources.s; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(704 + Int32.Parse(TextSpeed.Text)); break; case 't': str = Properties.Resources.t; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(571 + Int32.Parse(TextSpeed.Text)); break; case 'u': str = Properties.Resources.u; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(707 + Int32.Parse(TextSpeed.Text)); break; case 'v': str = Properties.Resources.v; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(646 + Int32.Parse(TextSpeed.Text)); break; case 'w': str = Properties.Resources.w; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(580 + Int32.Parse(TextSpeed.Text)); break; case 'x': str = Properties.Resources.x; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(636 + Int32.Parse(TextSpeed.Text)); break; case 'y': str = Properties.Resources.y; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(666 + Int32.Parse(TextSpeed.Text)); break; case 'z': str = Properties.Resources.z; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(486 + Int32.Parse(TextSpeed.Text)); break; case '0': str = Properties.Resources.n0; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(503 + Int32.Parse(TextSpeed.Text)); break; case '1': str = Properties.Resources.n1; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(463 + Int32.Parse(TextSpeed.Text)); break; case '2': str = Properties.Resources.n2; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(418 + Int32.Parse(TextSpeed.Text)); break; case '3': str = Properties.Resources.n3; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(450 + Int32.Parse(TextSpeed.Text)); break; case '4': str = Properties.Resources.n4; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(507 + Int32.Parse(TextSpeed.Text)); break; case '5': str = Properties.Resources.n5; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(582 + Int32.Parse(TextSpeed.Text)); break; case '6': str = Properties.Resources.n6; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(582 + Int32.Parse(TextSpeed.Text)); break; case '7': str = Properties.Resources.n7; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(520 + Int32.Parse(TextSpeed.Text)); break; case '8': str = Properties.Resources.n8; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(373 + Int32.Parse(TextSpeed.Text)); break; case '9': str = Properties.Resources.n9; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(523 + Int32.Parse(TextSpeed.Text)); break; case '.': str = Properties.Resources.dot; sp = new SoundPlayer(str); sp.Play(); Thread.Sleep(663 + Int32.Parse(TextSpeed.Text)); break; case ' ': Thread.Sleep(Math.Abs(Int32.Parse(TextSpeed.Text))); break; } } } try { glc.Stop(); glc.Dispose(); } catch{} la.Stop(); la.Dispose(); wfo.Dispose(); wc.Dispose(); wfr.Dispose(); GC.Collect(); }
//Сделали щелчки private void glctick(object sender, ElapsedEventArgs e) { WaveFileReader wfra = new WaveFileReader(Properties.Resources.glitch); WaveChannel32 wcs = new WaveChannel32(wfra, vol, 0); DirectSoundOut wfod = new DirectSoundOut(); wfod.Init(wcs); wfod.Play(); }
private void button6_Click(object sender, EventArgs e) { textBox2.Text = null; Dictionary <String, char> morse2 = new Dictionary <String, char>() { { ".-", 'A' }, { ".-.-", 'Ą' }, { "-...", 'B' }, { "-.-.", 'C' }, { "-.-..", 'Ć' }, { "-..", 'D' }, { ".", 'E' }, { "..-..", 'Ę' }, { "..-.", 'F' }, { "--.", 'G' }, { "....", 'H' }, { "..", 'I' }, { ".---", 'J' }, { "-.-", 'K' }, { ".-..", 'L' }, { ".-..-", 'Ł' }, { "--", 'M' }, { "-.", 'N' }, { "--.--", 'Ń' }, { "---", 'O' }, { "---.", 'Ó' }, { ".--.", 'P' }, { "--.-", 'Q' }, { ".-.", 'R' }, { "...", 'S' }, { "...-...", 'Ś' }, { "-", 'T' }, { "..-", 'U' }, { "...-", 'V' }, { ".--", 'W' }, { "-..-", 'X' }, { "-.--", 'Y' }, { "--..", 'Z' }, { "--..-.", 'Ż' }, { "--..-", 'Ź' }, { "-----", '0' }, { ".----", '1' }, { "..---", '2' }, { "...--", '3' }, { "....-", '4' }, { ".....", '5' }, { "-....", '6' }, { "--...", '7' }, { "---..", '8' }, { "----.", '9' }, }; OpenFileDialog open = new OpenFileDialog(); open.Filter = "Wave File (*.wav)|*.wav;"; if (open.ShowDialog() != DialogResult.OK) { return; } DisposeWave(); wave = new NAudio.Wave.WaveFileReader(open.FileName); customWaveViewer1.WaveStream = new NAudio.Wave.WaveFileReader(open.FileName); AudioFileReader readertest = new AudioFileReader(open.FileName); customWaveViewer1.Visible = true; label4.Visible = true; int bytesnumber = (int)readertest.Length; var buffer = new float[bytesnumber]; readertest.Read(buffer, 0, bytesnumber); String xxx = null; String odszyfrowane = null; int i = 0; int poczatekbipa = 0; int koniecbipa = 0; while (i < buffer.Length - 1) { while (buffer[i] < 0.2 && buffer[i] > -0.2 && i < buffer.Length - 1) { i++; } poczatekbipa = i; while (buffer[i] != 0 && i < buffer.Length - 1) { i++; } if (poczatekbipa - koniecbipa > 176500 && poczatekbipa - koniecbipa < 530000 && koniecbipa != 0) { odszyfrowane = odszyfrowane + '/'; } if (poczatekbipa - koniecbipa > 530000) { odszyfrowane = odszyfrowane + "//"; } koniecbipa = i; if (koniecbipa - poczatekbipa > 21180) { Console.WriteLine("Poczatek: " + poczatekbipa + " Koniec:" + koniecbipa); int dlugoscbipa = koniecbipa - poczatekbipa; Console.WriteLine("Długość bipa w probkach= " + dlugoscbipa); int dlugoscbipawsek = dlugoscbipa / 353; Console.WriteLine("Długość bipa w sekundach= " + dlugoscbipawsek); if (dlugoscbipawsek < 130) { Console.WriteLine("Bip krótki "); odszyfrowane = odszyfrowane + '.'; } else { Console.WriteLine("Bip długi"); odszyfrowane = odszyfrowane + '-'; } } } Console.Write("Odszyfrowana zawartosc to: " + odszyfrowane); char[] tablica2 = null; tablica2 = odszyfrowane.ToCharArray(); Console.WriteLine(); string slowo = null; string odszyfrowanawiadomosc = null; for (int x = 0; x < odszyfrowane.Length; x++) { if (tablica2[x] != '/') { slowo = slowo + tablica2[x]; } else { if (slowo == null) { odszyfrowanawiadomosc = odszyfrowanawiadomosc + ' '; } else if (morse2.ContainsKey(slowo)) { odszyfrowanawiadomosc = odszyfrowanawiadomosc + morse2[slowo]; } slowo = null; } } textBox3.Text = odszyfrowanawiadomosc; Console.WriteLine("Odszyfrowana wiadomość to: " + odszyfrowanawiadomosc); MessageBox.Show(Convert.ToString(buffer.Length)); output = new NAudio.Wave.DirectSoundOut(); output.Init(new NAudio.Wave.WaveChannel32(wave)); output.Play(); }
void worker_DoWork(object sender, DoWorkEventArgs e) { WAVFile input = new WAVFile(); input.Open("INPUT.wav", WAVFile.WAVFileMode.READ); WAVFile output = new WAVFile(); output.Create("PITCHY_OUTPUT.wav", input.IsStereo, input.SampleRateHz, input.BitsPerSample); //shift audio while (input.NumSamplesRemaining > 0) { short sample = input.GetNextSampleAs16Bit(); float sampleVal = (float)sample / 32768f; float[] indata = new float[] { sampleVal }; PitchShifter.PitchShift(0.5f, 1, input.SampleRateHz, indata); output.AddSample_16bit((short)(indata[0] * 32768)); } output.Close(); //play sound var soundFile = "PITCHY_OUTPUT.wav"; using (var wfr = new WaveFileReader(soundFile)) using (WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false }) using (var audioOutput = new DirectSoundOut()) { audioOutput.Init(wc); audioOutput.Play(); while (audioOutput.PlaybackState != PlaybackState.Stopped) { Thread.Sleep(20); } audioOutput.Stop(); } }
static void PlayUsingNAudio(String soundFile) { // The hard way. // http://naudio.codeplex.com/documentation // http://naudio.codeplex.com/wikipage?title=WAV using (var wfr = new WaveFileReader(soundFile)) using (WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false }) using (var audioOutput = new DirectSoundOut()) { audioOutput.Init(wc); audioOutput.Play(); while (audioOutput.PlaybackState != PlaybackState.Stopped) { Thread.Sleep(20); } audioOutput.Stop(); } }
static void Main(string[] args) { IWavePlayer waveOutDevice; WaveStream mainOutputStream; // 16 bit FLAC string fileName = @"Spark2.flac"; // 24 bit FLAC //string fileName = @"PASC183_24test.flac"; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Initiailizing NAudio"); Console.ResetColor(); try { waveOutDevice = new DirectSoundOut(50); } catch (Exception driverCreateException) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format("{0}", driverCreateException.Message)); return; } mainOutputStream = CreateInputStream(fileName); try { waveOutDevice.Init(mainOutputStream); } catch (Exception initException) { Console.WriteLine(String.Format("{0}", initException.Message), "Error Initializing Output"); return; } Console.WriteLine("NAudio Total Time: " + (mainOutputStream as WaveChannel32).TotalTime); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Playing FLAC.."); Console.ResetColor(); waveOutDevice.Volume = 1.0f; waveOutDevice.Play(); TestSeekPosition(mainOutputStream, new TimeSpan(0, 0, 10)); TestSeekPosition(mainOutputStream, new TimeSpan(0, 0, 30)); TestSeekPosition(mainOutputStream, new TimeSpan(0, 0, 00)); TestSeekPosition(mainOutputStream, new TimeSpan(0, 4, 04)); TestSeekPosition(mainOutputStream, new TimeSpan(0, 0, 09)); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Hit key to stop.."); Console.ResetColor(); Console.ReadKey(); waveOutDevice.Stop(); Console.WriteLine("Finished.."); mainOutputStream.Dispose(); waveOutDevice.Dispose(); Console.WriteLine("Press key to exit..."); Console.ReadKey(); }
private void WaveControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) { stopPlayer(); if (m_Dragging) { if (cursorEvent != null) { // Have finished dragging - fire event cursorEvent.Cursor.FireCursorMoveFinished(cursorEvent); cursorEvent = null; } m_Dragging = false; } else if(!m_PlayerJustStopped) { if (m_Wavefile != null) { if (m_DragStart == null || Math.Abs(e.X - m_DragStart.X) > 5 || Math.Abs(e.Y - m_DragStart.Y) > 5) return; // Ignore everything except click float start = m_StartSeconds; // Where to start playing float end = m_StartSeconds + m_LengthSeconds; // and end float pixelsPerSecond = Width / m_LengthSeconds; if (m_Cursors != null) { // Play only between cursors for (int i = 0; i < m_Cursors.Length; i++) { PositionCursor c = m_Cursors[i]; if (!c.Active) continue; float x = (c.Position - m_StartSeconds) * pixelsPerSecond; if (x <= e.X) start = Math.Max(start, c.Position); else end = Math.Min(end, c.Position); } } // If click not near start, start from click position float sx = (start - m_StartSeconds) * pixelsPerSecond; if (e.X - sx > 20) start = m_StartSeconds + e.X / pixelsPerSecond; m_Wavefile.Position = WaveFormat.SecondsToBytes(start); NotifyingSampleProvider p = new NotifyingSampleProvider(new OffsetSampleProvider(m_Wavefile) { Take = new TimeSpan((long)(10000000 * (end - start))) }); p.Sample += SampleCounter; // To keep track of samples played, for play position cursor m_SampleCount = (int)(start * WaveFormat.SampleRate); // Play position, in samples m_Timer.Interval = (int)(1000 / pixelsPerSecond); // Should fire about every pixel m_Timer.Start(); m_CurrentPlayer = m_Player = new NAudio.Wave.DirectSoundOut(); m_Player.PlaybackStopped += PlaybackStopped; if(Control.ModifierKeys == Keys.Control) // Play filtered sound m_Player.Init(new FilteredSampleProvider(p, Properties.Settings.Default.SilenceFilterCentre, Properties.Settings.Default.SilenceFilterQ)); else { // Play wave file } m_Player.Init(p); m_Player.Play(); Refresh(); } } } m_PlayerJustStopped = false; }
private void PlayWithNAudio() { if (!IsConcurent || _waveStream == null || _waveStream.Position == _waveStream.Length) { _waveStream = new WaveFileReader(_sample); var superWavStream32 = processWaveStream(_waveStream); _player = new DirectSoundOut(50); _player.Init(superWavStream32); _player.Volume = 1.0f; _player.Play(); } }
/// <summary> /// Called from main form when selecting Direct Sound device. /// </summary> /// <param name="guid"></param> public void setGUID(Guid guid) { deviceOutID = DEVICEID.DIRECTSOUND; DirectSoundOut directSoundOut; if (deviceOut != null) { deviceOut.PlaybackStopped -= loadNextSong; if (deviceOut.PlaybackState == PlaybackState.Playing) { deviceOut.Pause(); directSoundOut = new DirectSoundOut(guid); if (postVolumeMeter != null) directSoundOut.Init(postVolumeMeter); directSoundOut.Play(); changedDevice = false; } else { directSoundOut = new DirectSoundOut(guid); if (postVolumeMeter != null) directSoundOut.Init(postVolumeMeter); if (deviceOut.PlaybackState == PlaybackState.Paused) changedDevice = true; } deviceOut.Dispose(); } else { directSoundOut = new DirectSoundOut(guid); changedDevice = false; } directSoundOut.PlaybackStopped += loadNextSong; deviceOut = directSoundOut; }
void MStreamNewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs) { if (eventArgs.Frame != null) { UnmanagedImage umi = UnmanagedImage.FromManagedImage(eventArgs.Frame); videoPlayback1.LastFrame = umi.ToManagedImage(); } if (_firstFrame) { videoPlayback1.ResetActivtyGraph(); videoPlayback1.Duration = TimeSpan.FromMilliseconds(_mStream.Duration).ToString().Substring(0, 8); _firstFrame = false; if (_mStream.RecordingFormat != null) { _mStream.Listening = true; _mStream.WaveOutProvider.BufferLength = _mStream.WaveOutProvider.WaveFormat.AverageBytesPerSecond*2; _mStream.VolumeProvider = new VolumeWaveProvider16New(_mStream.WaveOutProvider); WaveOut = new DirectSoundOut(100); WaveOut.Init(_mStream.VolumeProvider); WaveOut.Play(); } } videoPlayback1.Time = TimeSpan.FromMilliseconds(_mStream.Time).ToString().Substring(0, 8); var pc = Convert.ToDouble(_mStream.Time)/_mStream.Duration; var newpos = pc * 100d; if (newpos < 0) newpos = 0; if (newpos > 100) newpos = 100; videoPlayback1.Value = newpos; }
private void StreamMP3() { var webRequest = (HttpWebRequest)WebRequest.Create(_source); HttpWebResponse resp = null; try { resp = (HttpWebResponse)webRequest.GetResponse(); } catch (WebException e) { if (e.Status != WebExceptionStatus.RequestCanceled) { } return; } byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame IMp3FrameDecompressor decompressor = null; try { using (var responseStream = resp.GetResponseStream()) { var readFullyStream = new ReadFullyStream(responseStream); while (!_stopEvent.WaitOne(0, false)) { if (_bufferedWaveProvider != null && _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes < _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4) { //Debug.WriteLine("Buffer getting full, taking a break"); Thread.Sleep(100); } else { Mp3Frame frame = null; try { frame = Mp3Frame.LoadFromStream(readFullyStream); } catch (EndOfStreamException) { // reached the end of the MP3 file / stream break; } catch (WebException) { // probably we have aborted download from the GUI thread break; } if (decompressor == null) { // don't think these details matter too much - just help ACM select the right codec // however, the buffered provider doesn't know what sample rate it is working at // until we have a frame WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); decompressor = new AcmMp3FrameDecompressor(waveFormat); this._bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat) {BufferDuration = TimeSpan.FromSeconds(5)}; _waveOut = new DirectSoundOut(1000); _waveOut.Init(_bufferedWaveProvider); _waveOut.Play(); _waveOut.PlaybackStopped += wavePlayer_PlaybackStopped; } int decompressed = decompressor.DecompressFrame(frame, buffer, 0); //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed)); _bufferedWaveProvider.AddSamples(buffer, 0, decompressed); } if (_stopEvent.WaitOne(0, false)) break; } Debug.WriteLine("Exiting"); // was doing this in a finally block, but for some reason // we are hanging on response stream .Dispose so never get there if (decompressor != null) { decompressor.Dispose(); decompressor = null; } } } finally { if (decompressor != null) { decompressor.Dispose(); } if (_waveOut!=null) { _waveOut.Stop(); } } }