NativeDirectSoundOut using DirectSound COM interop. Contact author: Alexandre Mutel - alexandre_mutel at yahoo.fr Modified by: Graham "Gee" Plumb
Inheritance: IWavePlayer
Esempio n. 1
1
        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();
        }
Esempio n. 2
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 ");
     }
 }
Esempio n. 3
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;
        }
Esempio n. 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();
            }
        }
Esempio n. 5
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();
            }
        }
Esempio n. 6
0
        // Method needed to cleanup outputStream and waveOut file
        private void DisposeWave()
        {
            if (sourceStream != null)
            {
                sourceStream.StopRecording();
                sourceStream.Dispose();
                sourceStream = null;
            }
            if (waveWriter != null)
            {
                waveWriter.Dispose();
                waveWriter = null;
            }

            if (waveOut != null)
            {
                if (waveOut.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                {
                    waveOut.Stop();
                }
                waveOut.Dispose();
                waveOut.Stop();
                waveOut = null;
            }

            if (waveReader != null)
            {
                waveReader.Dispose();
                waveReader.Close();
                waveReader = null;
            }
        }
Esempio n. 7
0
 // 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));
 }
Esempio n. 8
0
		public DirectSoundPlayer(INetworkChatCodec c)
			: base(c)
		{
			waveProvider = new BufferedWaveProvider(codec.RecordFormat);
			wavePlayer = new DirectSoundOut();
			wavePlayer.Init(waveProvider);
		}
Esempio n. 9
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);
        }
Esempio n. 10
0
        private void Stoprecording()
        {
            if (m_timer != null)
            {
                m_timer.Stop();
            }

            {
                if (sourceStream != null)
                {
                    if (waveOut != null) //stops sound from playing and disposes
                    {
                        waveOut.Stop();
                        waveOut.Dispose();
                        waveOut = null;
                    }
                    if (sourceStream != null) //stops sourcestream from recording and disposes
                    {
                        sourceStream.StopRecording();
                        sourceStream.Dispose();
                        sourceStream = null;
                    }

                    return;
                }
            }
        }
Esempio n. 11
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();
     }
 }
Esempio n. 12
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();
        }
Esempio n. 13
0
        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)
                {

                }
            });
        }
Esempio n. 14
0
 public ScoreMusicPlayer()
 {
     _syncObject  = new object();
     _waveStream  = new WaveMixerStream32();
     _soundPlayer = new AudioOut();
     _soundPlayer.Init(_waveStream);
     _channels = new Dictionary <WaveStream, WaveChannel32>();
 }
Esempio n. 15
0
 public Music(string path)
 {
     DisposeMusic();
     WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(path));
     stream = new BlockAlignReductionStream(pcm);
     output = new DirectSoundOut();
     output.Init(stream);
 }
Esempio n. 16
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;
 }
Esempio n. 17
0
 private void InitializeDirectSound()
 {
     lock (this.m_LockObject)
     {
         this.directSound = null;
         DirectSoundOut.DirectSoundCreate(ref this.device, out this.directSound, IntPtr.Zero);
         if (this.directSound != null)
         {
             this.directSound.SetCooperativeLevel(DirectSoundOut.GetDesktopWindow(), DirectSoundOut.DirectSoundCooperativeLevel.DSSCL_PRIORITY);
             DirectSoundOut.BufferDescription bufferDescription = new DirectSoundOut.BufferDescription();
             bufferDescription.dwSize        = Marshal.SizeOf(bufferDescription);
             bufferDescription.dwBufferBytes = 0u;
             bufferDescription.dwFlags       = DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_PRIMARYBUFFER;
             bufferDescription.dwReserved    = 0;
             bufferDescription.lpwfxFormat   = IntPtr.Zero;
             bufferDescription.guidAlgo      = Guid.Empty;
             object obj;
             this.directSound.CreateSoundBuffer(bufferDescription, out obj, IntPtr.Zero);
             this.primarySoundBuffer = (DirectSoundOut.IDirectSoundBuffer)obj;
             this.primarySoundBuffer.Play(0u, 0u, DirectSoundOut.DirectSoundPlayFlags.DSBPLAY_LOOPING);
             this.samplesFrameSize = this.MsToBytes(this.desiredLatency);
             DirectSoundOut.BufferDescription bufferDescription2 = new DirectSoundOut.BufferDescription();
             bufferDescription2.dwSize        = Marshal.SizeOf(bufferDescription2);
             bufferDescription2.dwBufferBytes = (uint)(this.samplesFrameSize * 2);
             bufferDescription2.dwFlags       = (DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_CTRLVOLUME | DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_CTRLPOSITIONNOTIFY | DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_STICKYFOCUS | DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_GLOBALFOCUS | DirectSoundOut.DirectSoundBufferCaps.DSBCAPS_GETCURRENTPOSITION2);
             bufferDescription2.dwReserved    = 0;
             GCHandle gchandle = GCHandle.Alloc(this.waveFormat, GCHandleType.Pinned);
             bufferDescription2.lpwfxFormat = gchandle.AddrOfPinnedObject();
             bufferDescription2.guidAlgo    = Guid.Empty;
             this.directSound.CreateSoundBuffer(bufferDescription2, out obj, IntPtr.Zero);
             this.secondaryBuffer = (DirectSoundOut.IDirectSoundBuffer)obj;
             gchandle.Free();
             DirectSoundOut.BufferCaps bufferCaps = new DirectSoundOut.BufferCaps();
             bufferCaps.dwSize = Marshal.SizeOf(bufferCaps);
             this.secondaryBuffer.GetCaps(bufferCaps);
             this.nextSamplesWriteIndex = 0;
             this.samplesTotalSize      = bufferCaps.dwBufferBytes;
             this.samples = new byte[this.samplesTotalSize];
             DirectSoundOut.IDirectSoundNotify directSoundNotify = (DirectSoundOut.IDirectSoundNotify)obj;
             this.frameEventWaitHandle1 = new EventWaitHandle(false, EventResetMode.AutoReset);
             this.frameEventWaitHandle2 = new EventWaitHandle(false, EventResetMode.AutoReset);
             this.endEventWaitHandle    = new EventWaitHandle(false, EventResetMode.AutoReset);
             DirectSoundOut.DirectSoundBufferPositionNotify[] array = new DirectSoundOut.DirectSoundBufferPositionNotify[3];
             array[0]              = default(DirectSoundOut.DirectSoundBufferPositionNotify);
             array[0].dwOffset     = 0u;
             array[0].hEventNotify = this.frameEventWaitHandle1.SafeWaitHandle.DangerousGetHandle();
             array[1]              = default(DirectSoundOut.DirectSoundBufferPositionNotify);
             array[1].dwOffset     = (uint)this.samplesFrameSize;
             array[1].hEventNotify = this.frameEventWaitHandle2.SafeWaitHandle.DangerousGetHandle();
             array[2]              = default(DirectSoundOut.DirectSoundBufferPositionNotify);
             array[2].dwOffset     = uint.MaxValue;
             array[2].hEventNotify = this.endEventWaitHandle.SafeWaitHandle.DangerousGetHandle();
             directSoundNotify.SetNotificationPositions(3u, array);
         }
     }
 }
Esempio n. 18
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);
        }
Esempio n. 19
0
        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();
        }
Esempio n. 20
0
 //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
 }
Esempio n. 21
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();
        }
Esempio n. 22
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;
            }
        }
Esempio n. 23
0
        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();
        }
Esempio n. 24
0
        public void Open()
        {
            _finished = false;

            _circularBuffer = new CircularSampleBuffer(BufferSize * BufferCount);

            _context = new DirectSoundOut(100);
            _context.Init(this);

            OnReadyChanged(true);
        }
Esempio n. 25
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();
        }
Esempio n. 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Song"/> class.
        /// </summary>
        /// <param name="URI">The URI to be loaded.</param>
        /// <param name="play">if set to <c>true</c> then the song will automatically play once loaded</param>
        public Song(string URI, bool play = false)
        {
            this.URI = URI;
            this.provider = MakeSong(this.URI);
            this.output = new DirectSoundOut(100);
            this.output.Init(provider);

            this.output.PlaybackStopped += output_PlaybackStopped;

            if (play)
                this.Play();
        }
Esempio n. 27
0
        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();
        }
Esempio n. 28
0
        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;
        }
Esempio n. 29
0
        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);
        }
Esempio n. 30
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();
        }
Esempio n. 31
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();
 }
Esempio n. 32
0
 private void DisposeWave()
 {
     if (SoundOut != null)
     {
         if (SoundOut.PlaybackState == NAudio.Wave.PlaybackState.Playing) SoundOut.Stop();
         SoundOut.Dispose();
         SoundOut = null;
     }
     if (BlockStream != null)
     {
         BlockStream.Dispose();
         BlockStream = null;
     }
 }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (soundOut != null)
            {
                soundOut.Stop();
                soundOut.Dispose();
                soundOut = null;
            }

            if (waveFileReader != null)
            {
                waveFileReader.Dispose();
                waveFileReader = null;
            }
        }
Esempio n. 34
0
 public void editorSesDinlemeDurdur()
 {
     if (waveOut != null)
     {
         waveOut.Stop();
         waveOut.Dispose();
         waveOut = null;
     }
     if (sourceStream != null)
     {
         sourceStream.StopRecording();
         sourceStream.Dispose();
         sourceStream = null;
     }
 }
Esempio n. 35
0
 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);
			}
		}
Esempio n. 37
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;
        }
Esempio n. 38
0
        private void button_stop_Click(object sender, EventArgs e)
        {
            waveOut?.Stop();
            waveOut?.Dispose();
            waveOut = null;

            sourceStream?.StopRecording();
            sourceStream?.Dispose();
            sourceStream = null;

            waveWriter?.Dispose();
            waveWriter = null;

            //Label
            this.Label_Status.Text = "待機中";
        }
Esempio n. 39
0
 // gebruikte resources opruimen
 public void DisposeMusic()
 {
     if (output != null)
     {
         if (output.PlaybackState == PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
Esempio n. 40
0
File: Form1.cs Progetto: sbst/code
        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; //флаг о потоке
        }
Esempio n. 41
0
 private void DisposeWave()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (wave != null)
     {
         wave.Dispose();
         wave = null;
     }
 }
Esempio n. 42
0
 public void MP3CloseFile()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
Esempio n. 43
0
 private void DisposeWave()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
 }
Esempio n. 44
0
        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;
            }
        }
Esempio n. 45
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 !");
            }
        }
Esempio n. 46
0
 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;
 }
Esempio n. 47
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();
        }
Esempio n. 48
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();
        }
Esempio n. 49
0
        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();
            }
        }
Esempio n. 50
0
        public void Play(string filename)
        {
            if (InvokeRequired)
                Invoke(new PlayDelegate(Play), filename);
            else
            {
                if (_mStream != null)
                {
                    _mStream.Stop();
                }

                if (WaveOut != null)
                {
                    WaveOut.Stop();
                    WaveOut.Dispose();
                    WaveOut = null;
                }

                _mStream = new FFMPEGStream(filename);
                _mStream.NewFrame += MStreamNewFrame;
                _mStream.DataAvailable += _mStream_DataAvailable;
                _mStream.LevelChanged += _mStream_LevelChanged;
                _mStream.PlayingFinished += _mStream_PlayingFinished;
                _mStream.RecordingFormat = null;

                _firstFrame = true;

                _filename = filename;
                _mStream.Start();
                _mStream.Play();

                string[] parts = filename.Split('\\');
                string fn = parts[parts.Length - 1];
                FilesFile ff =
                    ((MainForm) Owner).GetCameraWindow(ObjectID).FileList.FirstOrDefault(p => p.Filename.EndsWith(fn));
                videoPlayback1.Init(ff);

                videoPlayback1.CurrentState = VideoPlayback.PlaybackState.Playing;

            }
        }
Esempio n. 51
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();
        }
Esempio n. 52
0
        /// <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);
        }
Esempio n. 53
0
        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);
            }
        }
Esempio n. 54
0
        private void Player_FormClosing(object sender, FormClosingEventArgs e)
        {
            try {_mStream.Stop();} catch
            {
            }

            if (WaveOut != null)
            {
                WaveOut.Stop();
                WaveOut.Dispose();
                WaveOut = null;
            }
        }
Esempio n. 55
0
 /*
  * Cloture le record
  */
 private void StopRecord_OnClick(object sender, RoutedEventArgs e)
 {
     if (waveOut != null)
     {
         waveOut.Stop();
         waveOut.Dispose();
         waveOut = null;
     }
     if (sourceStream != null)
     {
         sourceStream.StopRecording();
         sourceStream.Dispose();
         sourceStream = null;
     }
     if (waveWriter != null)
     {
         waveWriter.Dispose();
         waveWriter = null;
     }
     ProgressBarVolume.Value = 0;
     Encode();
     var result = (MessageBoxResult)MessageBox.Show("Enregistrement termine", "Enregistrement");
 }
Esempio n. 56
0
        //Организовали зацикливание помех
        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();
        }
Esempio n. 57
0
        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();
        }
Esempio n. 58
0
        //Сделали щелчки
        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();
        }
Esempio n. 59
0
        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;
        }
Esempio n. 60
0
        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();
            }
        }