Play() public method

Begin playback
public Play ( ) : void
return void
コード例 #1
1
ファイル: Program.cs プロジェクト: mattcuba/practicesharp
        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();
        }
コード例 #2
0
        //Button to play music
        private void BtnPlay_Click(object sender, EventArgs e)
        {
            //caught NullException
            //handlings state if there is no sound
            if (output == null)
            {
                MessageBox.Show("Click local files to play a song.", "",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            { //if Playback state is paused
                if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
                {
                    output.Play();
                    //if playback state is playing current song
                }
                else if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                {
                    output.Pause();
                }

                //hide buttons and show
                BtnPlay.Visible  = false;
                BtnPause.Visible = true;
            }
        }
コード例 #3
0
ファイル: SpeechLib.cs プロジェクト: radtek/DCEC
 public void MP3PausePlay()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Pause();
         }
         else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
         }
     }
 }
コード例 #4
0
        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();
            }
        }
コード例 #5
0
ファイル: AudioService.cs プロジェクト: pjmagee/swtor-caster
        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)
                {

                }
            });
        }
コード例 #6
0
        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();
            }
        }
コード例 #7
0
        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;
        }
コード例 #8
0
 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 ");
     }
 }
コード例 #9
0
        private void startBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sourceStream == null)
            {
                InitializeSound(); // sets up sourcestream, dataIn event, buffer and waveout for data to be sent
                timePassed = 300;
            }

            try
            {
                sourceStream.StartRecording();
                StartTimer();
                noteList   = new List <int>();
                NoteOnList = new List <NoteOnEvent>();
                waveOut.Play();
            }
            catch (NAudio.MmException exception) //this error may occur when no input device is connected
            {
                System.Windows.MessageBox.Show("No Input Device available");
            }
            catch (InvalidOperationException)
            {
            }
            if (m_pitchTracker == null)
            {
                m_pitchTracker            = new PitchTracker();     //initilises class for detecting pitch
                m_pitchTracker.SampleRate = m_sampleRate;           // sample rate is set to 44100.0f as standard
                //  m_pitchTracker.PitchDetected += OnPitchDetected;    //
                m_audioBuffer = new float[(int)Math.Round(m_sampleRate * m_timeInterval / 1000.0)];
            }
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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();
        }
コード例 #12
0
 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();
     }
 }
コード例 #13
0
 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;
 }
コード例 #14
0
        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();
        }
コード例 #15
0
ファイル: SoundController.cs プロジェクト: harving/JazzHands
        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();
        }
コード例 #16
0
        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);
        }
コード例 #17
0
        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;
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: mattcuba/practicesharp
        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();
        }
コード例 #19
0
        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();
        }
コード例 #20
0
 // Method to play wav file the path of which is in the wavOpenName variable
 private void play()
 {
     try
     {
         initPlay();
         waveOut.Play();
     }
     catch
     {
         MessageBox.Show("Error accured!!!\n\nOpen file or record voice");
     }
 }
コード例 #21
0
 private void BtnContinua_Click(object sender, EventArgs e)
 { // Verifica se tem alguma música pausada, se tiver ele da play
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
         }
     }
     // Ativa e desativa os botões
     BtnPause.Enabled    = true;
     BtnContinua.Enabled = false;
 }
コード例 #22
0
ファイル: App.xaml.cs プロジェクト: JohnStov/Theremin
        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();
        }
コード例 #23
0
ファイル: MainWindow.xaml.cs プロジェクト: Vertver/oiu_csharp
 // Благодаря этой кнопке можно создавать подобные с разными функциями
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Pause();
         }
         else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
         }
     }
 }
コード例 #24
0
ファイル: Form1.cs プロジェクト: Arturlo99/Audio-App-UP-Lab
 private void pauseBtn_Click(object sender, EventArgs e)
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Pause();
         }
         else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
         }
     }
 }
コード例 #25
0
ファイル: AudioSource.cs プロジェクト: craftadria/Veloengine
 private void Pause()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Pause();
         }
         else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
         }
     }
 }
コード例 #26
0
ファイル: NAudioPlayer.cs プロジェクト: dcr25568/mmbot
        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;
        }
コード例 #27
0
        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();
        }
コード例 #28
0
 // 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();
 }
コード例 #29
0
		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);
			}
		}
コード例 #30
0
        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;
        }
コード例 #31
0
 //Pauses music playback and stops trackbar
 public void Pause()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             Program.MainForm.StopTimer();
             output.Pause();
         }
         else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             output.Play();
             Program.MainForm.StartTimer();
         }
     }
 }
コード例 #32
0
ファイル: Form1.cs プロジェクト: torates/-e-ePlayer
        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;
            }
        }
コード例 #33
0
        //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 !");
            }
        }
コード例 #34
0
        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();
        }
コード例 #35
0
ファイル: NAudioBufferedPlayer.cs プロジェクト: Jc54/PlayMe
 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;
 }
コード例 #36
0
ファイル: Form1.cs プロジェクト: Arturlo99/Audio-App-UP-Lab
        //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;
        }
コード例 #37
0
ファイル: MainWindow.xaml.cs プロジェクト: Vertver/oiu_csharp
        // Простой обработчик данных - просто берет и проигрывает.
        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();
        }
コード例 #38
0
ファイル: CustomSound.cs プロジェクト: FreyYa/GranBlueHelper
        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();
            }
        }
コード例 #39
0
        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();
        }
コード例 #40
0
 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");
     }
 }
コード例 #41
0
        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();
        }
コード例 #42
0
ファイル: Music.cs プロジェクト: neowutran/ShinraMeter
        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);
            }
        }
コード例 #43
0
ファイル: MainWindow.xaml.cs プロジェクト: Cocotus/kinect
        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();
            }

        }
コード例 #44
0
ファイル: Program.cs プロジェクト: gkhays/AudioGhost
        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();
            }
        }
コード例 #45
0
ファイル: Form1.cs プロジェクト: 8box/AudioRecord
 // Кнопка записи звука с микрофона и отправляя его на выходной порт (воспроизведение)
 private void ListenToThisDevice_Click(object sender, EventArgs e)
 {
     if (sourceList.SelectedItems.Count == 0) return;
     int deviceNumber = sourceList.SelectedItems[0].Index;
     _sourceStream = new WaveIn();
     _sourceStream.DeviceNumber = deviceNumber;
     _sourceStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(deviceNumber).Channels);
     WaveInProvider waveIn = new WaveInProvider(_sourceStream);
     _waveOut = new DirectSoundOut();
     _waveOut.Init(waveIn);
     _sourceStream.StartRecording();
     _waveOut.Play();
 }
コード例 #46
0
ファイル: Program.cs プロジェクト: mattcuba/practicesharp
        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();
        }
コード例 #47
0
ファイル: Sample.cs プロジェクト: AlexShkor/GestoMusic
        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();
            }
        }
コード例 #48
0
ファイル: Form1.cs プロジェクト: stdark/ABC-Encoder
        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();
        }
コード例 #49
0
ファイル: Program.cs プロジェクト: mattcuba/practicesharp
        static void Main(string[] args)
        {
            IWavePlayer waveOutDevice;
            WaveStream mainOutputStream;
            WaveChannel32 waveChannel;
            string fileName = @"No One's Gonna Love You.mp3";

            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, out waveChannel);
            try
            {
                waveOutDevice.Init(mainOutputStream);
            }
            catch (Exception initException)
            {
                Console.WriteLine(String.Format("{0}", initException.Message), "Error Initializing Output");
                return;
            }

            Console.WriteLine("NAudio Total Time: " + waveChannel.TotalTime);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Note: Please use good speakers or headphones, it is hard to notice equalizer changes with cheap/crappy laptop speakers...!");

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Playing File - Equalizer set to all Zero..");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Seeking to new time: 00:01:00..");
            waveChannel.CurrentTime = new TimeSpan(0, 1, 0);
            Console.ResetColor();

            waveOutDevice.Volume = 1.0f;
            waveOutDevice.Play();

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Hit key for next demo..");
            Console.ReadKey();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Playing File - Equalizer set to Full Treble/Fully Supressed Med..");
            waveOutDevice.Pause();
            m_eqEffect.HiGainFactor.Value = m_eqEffect.HiGainFactor.Maximum;
            m_eqEffect.MedGainFactor.Value = m_eqEffect.MedGainFactor.Minimum;
            m_eqEffect.LoGainFactor.Value = 0;
            m_eqEffect.OnFactorChanges();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Seeking to new time: 00:01:00..");
            waveChannel.CurrentTime = new TimeSpan(0, 1, 0);
            Console.ResetColor();

            waveOutDevice.Volume = 1.0f;
            waveOutDevice.Play();

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Hit key for next demo..");
            Console.ReadKey();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Playing File - Equalizer set to Full Bass..");
            waveOutDevice.Pause();
            m_eqEffect.HiGainFactor.Value = 0;
            m_eqEffect.MedGainFactor.Value = 0;
            m_eqEffect.LoGainFactor.Value = m_eqEffect.LoGainFactor.Maximum;
            m_eqEffect.OnFactorChanges();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Seeking to new time: 00:01:00..");
            waveChannel.CurrentTime = new TimeSpan(0, 1, 0);
            Console.ResetColor();

            waveOutDevice.Volume = 1.0f;
            waveOutDevice.Play();

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Hit key for next demo..");
            Console.ReadKey();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Playing File - Equalizer set to Full Bass and Full Treble..");
            waveOutDevice.Pause();
            m_eqEffect.HiGainFactor.Value = m_eqEffect.HiGainFactor.Maximum;
            m_eqEffect.MedGainFactor.Value = 0;
            m_eqEffect.LoGainFactor.Value = m_eqEffect.LoGainFactor.Maximum;
            m_eqEffect.OnFactorChanges();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Seeking to new time: 00:01:00..");
            waveChannel.CurrentTime = new TimeSpan(0, 1, 0);
            Console.ResetColor();

            waveOutDevice.Volume = 1.0f;
            waveOutDevice.Play();

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Hit key for next demo..");
            Console.ReadKey();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Playing File - Equalizer set to Full Med, Fully Supressed Bass and Treble..");
            waveOutDevice.Pause();
            m_eqEffect.HiGainFactor.Value = m_eqEffect.HiGainFactor.Minimum;
            m_eqEffect.MedGainFactor.Value = m_eqEffect.MedGainFactor.Maximum;
            m_eqEffect.LoGainFactor.Value = m_eqEffect.LoGainFactor.Minimum;
            m_eqEffect.OnFactorChanges();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Seeking to new time: 00:01:00..");
            waveChannel.CurrentTime = new TimeSpan(0, 1, 0);
            Console.ResetColor();

            waveOutDevice.Volume = 1.0f;
            waveOutDevice.Play();

            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();
        }
コード例 #50
0
 public void Play(SoundEffect type, float volume = 1.0F)
 {
     //_soundEffect?.Dispose();
     switch (type)
     {
         case SoundEffect.Move:
             _wfr = new WaveFileReader(Properties.Resources.Move);
             break;
         case SoundEffect.Confirm:
             _wfr = new WaveFileReader(Properties.Resources.Confirm);
             break;
         case SoundEffect.Cancel:
             _wfr = new WaveFileReader(Properties.Resources.Cance);
             break;
         case SoundEffect.Eliminate:
             _wfr = new WaveFileReader(Properties.Resources.Eliminate);
             break;
         case SoundEffect.EnemyAttack:
             _wfr = new WaveFileReader(Properties.Resources.EnemyAttack);
             break;
         case SoundEffect.Fail:
             _wfr = new WaveFileReader(Properties.Resources.Fail);
             break;
         case SoundEffect.GetItem:
             _wfr = new WaveFileReader(Properties.Resources.GetItem);
             break;
         case SoundEffect.OpenDoor:
             _wfr = new WaveFileReader(Properties.Resources.OpenDoor);
             break;
         case SoundEffect.PlayerAttack:
             _wfr = new WaveFileReader(Properties.Resources.PlayerAttack);
             break;
         case SoundEffect.Select:
             _wfr = new WaveFileReader(Properties.Resources.Select);
             break;
         default:
             throw new Exception("Not expected audioType.");
     }
     WaveChannel32 wc = new WaveChannel32(_wfr) { PadWithZeroes = false };
     _soundEffect = new DirectSoundOut();
     _soundEffect.Init(wc);
     _soundEffect.Volume = volume;
     _soundEffect.Play();
 }
コード例 #51
0
        private void PlayButton_Click(object sender, EventArgs e)
        {
            //  https://code.msdn.microsoft.com/windowsdesktop/Custom-Colored-ProgressBar-a68b61de
            // http://stackoverflow.com/questions/778678/how-to-change-the-color-of-progressbar-in-c-sharp-net-3-5

            txtMessage.Text = PLAYING_AUDIO;
            lblStop.Visible = false;
            PlayButton.Visible = false;
            PauseButton.Visible = true;
            ProgressBar.Visible = true;
            lblRecordTimer.Visible = true;

            tmrPlayBackTimer.Start();

            string strFileToPlay = outputFolder + "\\" + outputFilename;

            if (audioOutput != null ) // Playback is already in progress i.e. re-play after playback has been paused
            {
                audioOutput.Play();
                return;
            }

            // If the recorded file is present then play the attachment
            if (File.Exists(strFileToPlay))
            {
                String soundFile = strFileToPlay;
                wfr = new WaveFileReader(soundFile);
                WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false };
                audioOutput = new DirectSoundOut();
                {
                    audioOutput.PlaybackStopped += audioOutput_PlaybackStopped;
                    audioOutput.Init(wc);

                    audioOutput.Play();
                }
            }
            else
            {
                MessageBox.Show("Could not find the recorded file\n\nPlease try recording again", "Audio file not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #52
0
ファイル: WebStream.cs プロジェクト: WesleyYep/ispyconnect
        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();
                }
            }
        }
コード例 #53
0
 public void Test()
 {
     var wfr = new WaveFileReader(Properties.Resources.Move);
     WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false };
     using (var audioOuput = new DirectSoundOut())
     {
         audioOuput.Init(wc);
         audioOuput.Play();
     }
 }
コード例 #54
0
ファイル: BasicPlayer.cs プロジェクト: TheDizzler/DJMixer
        /// <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;
        }
コード例 #55
0
ファイル: Form1.cs プロジェクト: stdark/ABC-Encoder
        //Сделали щелчки
        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();
        }
コード例 #56
0
        // NAudio.Wave.WaveStream stream = null;
        private void button2_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;

            int deviceNumber = listView1.SelectedItems[0].Index;

            //waveOut = new NAudio.Wave.WaveOut(); ;
            sourceStream = new NAudio.Wave.WaveIn();
            sourceStream.DeviceNumber = deviceNumber;
            sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(48000, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);

            sourceStream.DataAvailable += new EventHandler<WaveInEventArgs>(sourceStream_DataAvailable);
            //waveWriter = new NAudio.Wave.WaveFileWriter(save.FileName, sourceStream.WaveFormat);

            sourceStream.BufferMilliseconds = 100;
            //wavebuffer = new NAudio.Wave.WaveBuffer();
            //bwp = new NAudio.Wave.BufferedWaveProvider(sourceStream.WaveFormat);
               // bwp.DiscardOnBufferOverflow = true;

            NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
            waveOut = new NAudio.Wave.DirectSoundOut();
            waveOut.Init(waveIn);

            sourceStream.StartRecording();
            //waveOut.Init(bwp);
            waveOut.Play();
               // sourceStream.StopRecording();
               // Start(sender,e);
            timer1.Enabled=true;

            ++count;
        }
コード例 #57
0
ファイル: Form1.cs プロジェクト: stdark/ABC-Encoder
        //Организовали зацикливание помех
        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();
        }
コード例 #58
0
		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;
		}
コード例 #59
0
ファイル: Player.cs プロジェクト: WesleyYep/ispyconnect
        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;
        }
コード例 #60
0
ファイル: CustomSound.cs プロジェクト: Sinwee/KanColleViewer
 public void SoundOutput(string header, bool IsWin8)
 {
     try
     {
         /**
      *
      * 출력할 소리가 wav인지 mp3인지 비프음인지 채크합니다.
      * windows8 이상의 경우에는 비프음보다 윈도우8 기본 알림음이 더 알맞다고 생각하기에 IsWin8이 True면 아무 소리도 내보내지 않습니다.
      *
     **/
         DisposeWave();//알림이 동시에 여러개가 울릴 경우 소리가 겹치는 문제를 방지
         string Audiofile = FileCheck(header);
         if (string.IsNullOrEmpty(Audiofile) && !IsWin8)
         {
             System.Media.SystemSounds.Beep.Play();
         }
         else if (!string.IsNullOrEmpty(Audiofile))
         {
             float Volume = Settings.Current.CustomSoundVolume > 0 ? (float)Settings.Current.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();
         }
     }
     catch(Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
         KanColleClient.Current.CatchedErrorLogWriter.ReportException(ex.Source, ex);
         System.Media.SystemSounds.Beep.Play();
     }
 }