当前位置: 首页>>代码示例>>C#>>正文


C# WaveOut.Stop方法代码示例

本文整理汇总了C#中NAudio.Wave.WaveOut.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# WaveOut.Stop方法的具体用法?C# WaveOut.Stop怎么用?C# WaveOut.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在NAudio.Wave.WaveOut的用法示例。


在下文中一共展示了WaveOut.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            // for recording
            waveFileWriter = new WaveFileWriter(@"C:\rec\out.wav", new WaveFormat(44100, 2));

            var sound = new MySound();
            sound.SetWaveFormat(44100, 2);
            sound.init();
            waveOut = new WaveOut();
            waveOut.Init(sound);
            waveOut.Play();

            ConsoleKeyInfo keyInfo;
            bool loop = true;
            while (loop)
            {
                keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.Q)
                {
                    waveOut.Stop();
                    waveOut.Dispose();
                    waveFileWriter.Close();
                    waveFileWriter.Dispose();
                    loop = false;
                }
            }
        }
开发者ID:ryo-okabayashi,项目名称:sound,代码行数:27,代码来源:Program.cs

示例2: Main

        static void Main(string[] args)
        {
            var adj = new AdjustableTFunc {Value = 1600};

            var tFuncWaveProvider = new TFuncWaveProvider
                {
            //                  Amplitude = TFunc.Sin(new Frequency(adj.TFunc))
            //                  Amplitude = TFunc.Sin(new Frequency(t => TFuncs.Sin(Frequency.Hertz(1))(t) + 1000))
                    Amplitude = TFunc.Sin(TFunc.Sin(Frequency.Hertz(2)) + 1000)
                };
            var waveOut = new WaveOut();
            waveOut.Init(tFuncWaveProvider);
            waveOut.Play();

            Console.WriteLine("Press q to kill");
            char k;
            while ((k = Console.ReadKey().KeyChar) != 'q')
            {
                if (k == 'u')
                {
                    adj.Value+=10;
                }
                if (k == 'd')
                {
                    adj.Value-=10;
                }
                Console.Write(" ");
                Console.WriteLine(adj.Value);
            }

            waveOut.Stop();
            waveOut.Dispose();
        }
开发者ID:rmichela,项目名称:Acoustico,代码行数:33,代码来源:Program.cs

示例3: PlayAsync

		private async Task PlayAsync(Action onFinished, Action<Viseme> onVisemeHit, CancellationToken token)
		{
			try
			{
				using (var m = new MemoryStream(_tts.waveStreamData))
				{
					using (var reader = new WaveFileReader(m))
					{
						using (var player = new WaveOut())
						{
							player.Init(reader);
							player.Play();

							var visemes = _tts.visemes;

							int nextViseme = 0;
							double nextVisemeTime = 0;

							while (player.PlaybackState == PlaybackState.Playing)
							{
								if (onVisemeHit != null)
								{
									var s = reader.CurrentTime.TotalSeconds;
									if (s >= nextVisemeTime)
									{
										var v = visemes[nextViseme];
										nextViseme++;
										if (nextViseme >= visemes.Length)
											nextVisemeTime = double.PositiveInfinity;
										else
											nextVisemeTime += v.duration;

										onVisemeHit(v.viseme);
									}
								}

								await Task.Delay(1);
								if (token.IsCancellationRequested)
									break;

								//Console.WriteLine("...next");
							}
							player.Stop();
							onFinished?.Invoke();
						}
					}
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				throw e;
			}
		}
开发者ID:GAIPS-INESC-ID,项目名称:FAtiMA-Toolkit,代码行数:54,代码来源:VoicePlayer.cs

示例4: PlayTone

 public void PlayTone(int frequency, double duration) {
     _sineWave.Frequency = frequency;
     ;
     _sineWave.SetWaveFormat(44100, 1);
     using (_waveOut = new WaveOut()) {
         _waveOut.DeviceNumber = 0;
         _waveOut.Init(_sineWave);
         _waveOut.Play();
         System.Threading.Thread.Sleep(2000);
         _waveOut.Stop();
         _waveOut = null;
     }
 }
开发者ID:aadennis,项目名称:TonesApp,代码行数:13,代码来源:NAudioSineWave.cs

示例5: DoAudioPlayback

        private void DoAudioPlayback()
        {
            var waveOut = new WaveOut();

            waveOut.DesiredLatency = 80;
            waveOut.Init(_waveProvider);

            waveOut.Play();

            while (IsPlaying)
            {
                Thread.Sleep(50);
            }

            waveOut.Stop();
        }
开发者ID:broosa,项目名称:KinectTheremin,代码行数:16,代码来源:ThereminAudio.cs

示例6: Main

        private static void Main(string[] args)
        {
            // Initialization
            Console.OutputEncoding = Encoding.UTF8;
            var ape = new ApeReader(args[0]);
            DisplayInformation(ape.Handle);

            // Set up the player.
            IWavePlayer player = new WaveOut();
            player.Init(ape);
            player.Play();

            // Listen for key presses to pause/play audio.
            var isPlaying = true;
            do
            {
                var keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.Spacebar)
                {
                    if (isPlaying)
                    {
                        player.Pause();
                        isPlaying = false;
                    }
                    else
                    {
                        player.Play();
                        isPlaying = true;
                    }
                }

                // If we hit the end of the stream in terms of actual audio data.
                if (isPlaying && ape.Position == ape.Length)
                {
                    player.Stop();
                }

            } while (player.PlaybackState != PlaybackState.Stopped);
        }
开发者ID:OronDF343,项目名称:MonkeysAudioSharp,代码行数:39,代码来源:Program.cs

示例7: Main

        static void Main(string[] args)
        {
            var waveOut = new WaveOut();
            var encoder = new Source();
            waveOut.Init(encoder);
            waveOut.Play();

            Stopwatch timer = new Stopwatch();
            timer.Start();
            while (timer.Elapsed < new TimeSpan(0, 0, 5))
            {
                encoder.SetTimecode(new LTCSharp.Timecode(
                    timer.Elapsed.Hours,
                    timer.Elapsed.Minutes,
                    timer.Elapsed.Seconds,
                    (int) ((float)timer.Elapsed.Milliseconds / 1000.0f * 30.0f)));
                Thread.Sleep(10);
            }
            timer.Stop();

            waveOut.Stop();
            waveOut.Dispose();
        }
开发者ID:sebllll,项目名称:LTCSharp,代码行数:23,代码来源:Program.cs

示例8: PlayMp3FromUrl

        public void PlayMp3FromUrl(string url)
        {
            using (Stream ms = new MemoryStream())
            {
                using (Stream stream = WebRequest.Create(url)
                    .GetResponse().GetResponseStream())
                {
                    byte[] buffer = new byte[32768];
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                }

                ms.Position = 0;
                using (WaveStream blockAlignedStream =
                    new BlockAlignReductionStream(
                        WaveFormatConversionStream.CreatePcmStream(
                            new Mp3FileReader(ms))))
                {
                    using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                    {
                        waveOut.Init(blockAlignedStream);
                        waveOut.PlaybackStopped += (sender, e) =>
                        {
                            waveOut.Stop();
                        };

                        waveOut.Play();
                        waiting = true;
                        stop.WaitOne(TimeWait);
                        waiting = false;
                    }
                }
            }
        }
开发者ID:Gaulford,项目名称:BitsOfBytes,代码行数:37,代码来源:Form1.cs

示例9: RunSession

    private void RunSession(WaveOut WaveOut, WaveStream stream, string match) {
      played.Add(match);
      WSRConfig.GetInstance().logInfo("PLAYER", "[" + device + "]" + "Start Player");
      Stopwatch timer = new Stopwatch(); timer.Start();

      using (WaveChannel32 volumeStream = new WaveChannel32(stream)) {
        volumeStream.Volume = match == "TTS" ? WSRConfig.GetInstance().SpkVolTTS / 100f : WSRConfig.GetInstance().SpkVolPlay / 100f;
        WaveOut.Init(volumeStream);
        WaveOut.Play();
        while (stream.CurrentTime < stream.TotalTime && played.Contains(match) && timer.ElapsedMilliseconds < 1000 * 60 * 8) {
          Thread.Sleep(100);
        }
        WaveOut.Stop();
        stream.Dispose();
      }

      WSRConfig.GetInstance().logInfo("PLAYER", "[" + device + "]" + "End Player");
      played.Remove(match);
    }
开发者ID:jdelhommeau,项目名称:WSRMacro,代码行数:19,代码来源:WSRSpeaker.cs

示例10: PlayMP3

        public bool PlayMP3(string fileName)
        {
            if (fileName == null) { return false; }

              if (fileName.StartsWith("http")) {
            return StreamMP3(fileName);
              }

              speaking = true;
              WSRConfig.GetInstance().logInfo("PLAYER", "Start MP3 Player");
              using (var ms = File.OpenRead(fileName))
              using (var mp3Reader = new Mp3FileReader(ms))
              using (var pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader))
              using (var baStream = new BlockAlignReductionStream(pcmStream))
              using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) {
            waveOut.Init(baStream);
            waveOut.Play();
            played.Add(fileName);
            while (baStream.CurrentTime < baStream.TotalTime && played.Contains(fileName)) {
              Thread.Sleep(100);
            }
            played.Remove(fileName);
            waveOut.Stop();

              }
              WSRConfig.GetInstance().logInfo("PLAYER", "End MP3 Player");
              speaking = false;
              return true;
        }
开发者ID:Oniric75,项目名称:WSRMacro,代码行数:29,代码来源:WSRSpeaker.cs

示例11: StreamMP3

        public bool StreamMP3(string url)
        {
            if (url == null) { return false; }

              speaking = true;
              WSRConfig.GetInstance().logInfo("PLAYER", "Stream MP3 Player");

              using (var ms = new MemoryStream())
              using (var stream = WebRequest.Create(url).GetResponse().GetResponseStream()) {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
              ms.Write(buffer, 0, read);
            }
            ms.Position = 0;
            using (var mp3Reader = new Mp3FileReader(ms))
            using (var pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader))
            using (var baStream = new BlockAlignReductionStream(pcmStream))
            using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) {
              waveOut.Init(baStream);
              waveOut.Play();
              played.Add(url);
              while (baStream.CurrentTime < baStream.TotalTime && played.Contains(url)) {
            Thread.Sleep(100);
              }
              played.Remove(url);
              waveOut.Stop();
            }
              }

              WSRConfig.GetInstance().logInfo("PLAYER", "End MP3 Player");
              speaking = false;
              return true;
        }
开发者ID:Oniric75,项目名称:WSRMacro,代码行数:34,代码来源:WSRSpeaker.cs

示例12: OnMp3RepositionTestClick

 private void OnMp3RepositionTestClick(object sender, EventArgs e)
 {
     var filename = SelectInputFile();
     if (filename == null) return;
     var wo = new WaveOut();
     var af = new AudioFileReader(filename);
     wo.Init(af);
     var f = new Form();
     var b = new Button() { Text = "Play" };
     b.Click += (s, a) => wo.Play();
     var b2 = new Button() { Text = "Stop", Left = b.Right };
     b2.Click += (s, a) => wo.Stop();
     var b3 = new Button { Text = "Rewind", Left = b2.Right };
     b3.Click += (s, a) => af.Position = 0;
     f.FormClosed += (s, a) => { wo.Dispose(); af.Dispose(); };
     f.Controls.Add(b);
     f.Controls.Add(b2);
     f.Controls.Add(b3);
     f.ShowDialog(this);
 }
开发者ID:LibertyLocked,项目名称:NAudio,代码行数:20,代码来源:SimplePlaybackPanel.cs

示例13: StartPlayingThisClip

 private void StartPlayingThisClip(AudioClipToPlay clip, double curSec)
 {
     cxzxc(string.Format("start of {0} {1}-{2}", clip.Filename, clip.SecFileStart, clip.SecFileEnd));
     // create the device
     IWavePlayer waveOutDevice = new WaveOut();
     var deviceAndShit = new DeviceAndItsData(waveOutDevice, clip);
     lock (this) { devicesPlaying.Add(deviceAndShit); }
     Thread ttt = new Thread(() =>
     {
         using (var reader = OpenAudioFile(clip.Filename))
         {
             deviceAndShit.WaveReader = reader;
             // init the playback stuff
             waveOutDevice.Init(reader);
             var syncOffsetSec = curSec - clip.SecOffset; // would be 0 if curSec == clip.SecOffset
             var clipSecStart = clip.SecFileStart + syncOffsetSec;
             var clipSecEnd = clip.SecFileEnd;
             reader.CurrentTime = TimeSpan.FromSeconds(clipSecStart + NAUDIO_SYNC_OFFSET);
             var endTs = TimeSpan.FromSeconds(clipSecEnd + NAUDIO_SYNC_OFFSET);
             var sleepTs = TimeSpan.FromSeconds(NAUDIO_SLEEP_FRAME_TIME);
             deviceAndShit.PlaybackStateRequest = PlaybackState.Playing;
             waveOutDevice.Play();
             while (reader.CurrentTime < endTs)
             {
                 Thread.Sleep(sleepTs);
                 if (waveOutDevice.PlaybackState == PlaybackState.Playing && deviceAndShit.PlaybackStateRequest == PlaybackState.Paused)
                     waveOutDevice.Pause();
                 if (waveOutDevice.PlaybackState == PlaybackState.Paused && deviceAndShit.PlaybackStateRequest == PlaybackState.Playing)
                     waveOutDevice.Play();
                 if (deviceAndShit.StopHasBeenInvoked)
                     break;
                 if (waveOutDevice.PlaybackState == PlaybackState.Stopped)
                     break;
             }
             waveOutDevice.Stop(); // no harm calling stop 2x right?
             lock (this) {
                 devicesPlaying.Remove(deviceAndShit);
                 devicesPaused.Remove(deviceAndShit);
             }
             cxzxc(string.Format("stop of {0} {1}-{2}", clip.Filename, clip.SecFileStart, clip.SecFileEnd));
         }
     });
     ttt.Start();
 }
开发者ID:miktemk,项目名称:VidkaEditor,代码行数:44,代码来源:AudioPlayerNAudio.cs

示例14: PlayInThread

        private void PlayInThread(object data)
        {
            string filename = (string)data;

            _waveOutDevice = new WaveOut();
            WaveChannel32 inputStream = null;
            WaveStream mp3Reader = null;

            try
            {
                if (SupportedFileTypes.CanBePlayed(filename))
                {
                    mp3Reader = new Mp3FileReader(filename);

                    inputStream = new WaveChannel32(mp3Reader);
                }
                else
                {
                    throw new InvalidOperationException("Unsupported extension");
                }

                _waveOutDevice.Init(inputStream);
                _waveOutDevice.Volume = _volume;
                _waveOutDevice.PlaybackStopped += _waveOutDevice_PlaybackStopped;
                _waveOutDevice.Play();

                Log.Debug("Playing " + filename);

                Thread.Sleep(mp3Reader.TotalTime);
            }
            catch (Exception exc)
            {
                Log.Debug("Error while playing song " + filename + ":" + exc.ToString());
            }
            finally
            {
                _waveOutDevice.Stop();
                if (mp3Reader!=null)
                    mp3Reader.Close();

                if (inputStream!=null)
                    inputStream.Close();

                _waveOutDevice.Dispose();
            }
        }
开发者ID:awlawl,项目名称:Maestro,代码行数:46,代码来源:NAudioInteractor.cs

示例15: SoundWord

        private void SoundWord()
        {
            // Считываем параметры с движков регуляторов

             // Беконечная работа - если слово условно звучит одну секунду, то это на 1 год
             if (infinity_work_flag)
                 numberofwords = 31536000;
             else
                 numberofwords = trackBar_N.Value;

             interval = trackBar_Pause.Value;

             speed = trackBar_Speed.Value;
             tone = trackBar_Tone.Value;

            // Инициализация звуковой карты (NAudio library)
            WaveOut MyWaveOut = new WaveOut();
            var sineWaveProvider = new SineWaveProvider32();
            sineWaveProvider.SetWaveFormat(16000, 1); // 16кГц, моно
            sineWaveProvider.Frequency = tone;          // Тон посылки
            sineWaveProvider.Amplitude = 0.5f;          // Амплитуда посылки
            MyWaveOut.Init(sineWaveProvider);

            // Воспроизведение слова
            int dot = speed_calibr / speed;    // Длительность точки
            int dash = 3 * dot;                // Длительность тире
            int dash_conjoint = dash;          // Промежуток между слитными буквами типа <KN>

            // Если стоит галка "Пауза при старте", то использовать паузу перед началом
            if (checkBox_StartPause.Checked)
            {
                startpause_flag = true;                // Использовать паузу
                Thread.Sleep(startpause * 1000);	   // Задержка в секундах перед началом передачи
            }

            // Выводим случайные слова из массива

            Random rnd = new Random();

            if(non_random_flag)
            {
                numberofwords = AllWords.Length;        // При отмене случайного выбора слов выводим все слова
            }                                           // один раз

            for (int i = 1; i <= numberofwords; i++)
            {
             int num;

             // Обрабатываем кнопку "СТОП"
             Application.DoEvents();
             if (!working_flag)
                 break;          //останавливаем воспроизведение слов

             if (!non_random_flag)
             {
                 num = rnd.Next(0, AllWords.Length);	// Номер случайного слова
             }
             else
             {
                 num = i-1;
             }

             string word = AllWords[num].ToUpper();     // Получаем случайное слово в верхнем
                                                        // регистре
             for (int j = 0; j < word.Length; j++)      // Перебираем буквы в слове
             {

                 // Обрабатываем кнопку "СТОП"
                 Application.DoEvents();
                 if (!working_flag)
                     break;          //останавливаем воспроизведение

                // Воспроизводим букву
                char symbol = word[j];

                // Слитные буквы для <AS> и т.п.
                if (symbol == '<')
                    dash_conjoint = dot;	            // "<" - слитное слово

                 if (symbol == '>')
                {
                    dash_conjoint = dash;			    // ">" - раздельное слово
                    Thread.Sleep(dash_conjoint);
                }

                    // Цифры
                    if(symbol == '0')
                    {
                        MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop(); Thread.Sleep(dot);
                        MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop(); Thread.Sleep(dot);
                        MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop(); Thread.Sleep(dot);
                        MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop(); Thread.Sleep(dot);
                        MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop();
                        Thread.Sleep(dash_conjoint);
                    }

                     if(symbol == '1')
                     {
                         MyWaveOut.Play(); Thread.Sleep(dot);  MyWaveOut.Stop(); Thread.Sleep(dot);
                         MyWaveOut.Play(); Thread.Sleep(dash); MyWaveOut.Stop(); Thread.Sleep(dot);
//.........这里部分代码省略.........
开发者ID:richmanfx,项目名称:cw_win_4,代码行数:101,代码来源:Cw_winForm.cs


注:本文中的NAudio.Wave.WaveOut.Stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。