public Init ( IWaveProvider waveProvider ) : void | ||
waveProvider | IWaveProvider | WaveProvider to play |
return | void |
public Call(IPEndPoint Address) { UdpSender = new UdpClient(); UdpSender.Connect(Address); this.Address = Address; _encoder = new SpeexEncoder(BandMode.Wide); SpeexProvider = new JitterBufferWaveProvider(); SoundOut = new WaveOutEvent(); SoundOut.Init(SpeexProvider); SoundOut.Play(); }
public AudioPlayer(Resource resource, TabPage tab) { var soundData = (Sound)resource.Blocks[BlockType.DATA]; var stream = soundData.GetSoundStream(); waveOut = new WaveOutEvent(); if (soundData.Type == Sound.AudioFileType.WAV) { var rawSource = new WaveFileReader(stream); waveOut.Init(rawSource); } else if (soundData.Type == Sound.AudioFileType.MP3) { var rawSource = new Mp3FileReader(stream); waveOut.Init(rawSource); } playButton = new Button(); playButton.Text = "Play"; playButton.TabIndex = 1; playButton.Size = new Size(100, 25); playButton.Click += PlayButton_Click; tab.Controls.Add(playButton); }
public mControllerPanel() { Console.OutputEncoding = System.Text.Encoding.Unicode; // Open mixer //mixer = new MixingWaveProvider32(); mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)); mixer.ReadFully = true; // Init sources satellite = new sourceSatellite(mixer); player1 = new sourcePlayer(mixer); player2 = new sourcePlayer(mixer); // Open output line //outputMaster = new DirectSoundOut(); outputMaster = new WaveOutEvent(); outputMaster.DesiredLatency = 700; outputMaster.Init(mixer); outputMaster.Play(); loadConfig(); ap = new mAutopilot(this); tsInterface.setController(this); tsInterface.pollServiceStart(); tsInterface.connect(); }
public static void PlayFromFile(string filename, int frequency) { using ( FileStream stream = new FileStream(filename, FileMode.Open)) { var waveFormat = WaveFormat.CreateMuLawFormat(frequency * 2, 1); var reader = new NAudio.Wave.RawSourceWaveStream(stream, waveFormat); using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)) { convertedStream.Seek(0, 0); WaveOutEvent player = new WaveOutEvent(); WaveChannel32 volumeStream = new WaveChannel32(convertedStream); player.Init(volumeStream); player.Play(); while (player.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); var input = Console.ReadKey(); if (input.KeyChar > 1) ; { player.Stop(); } } } } }
static AudioPlayer() { var output = new WaveOutEvent(); _mixer = new MixingSampleProvider( WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, ChannelCount)); _mixer.ReadFully = true; output.Init(_mixer); output.Play(); }
public NewCall(string CallID) { this.CallID = CallID; UdpConnection = new UdpClient(); UdpConnection.Connect("209.141.53.112", 25000); _encoder = new SpeexEncoder(BandMode.Wide); SpeexProvider = new JitterBufferWaveProvider(); SoundOut = new WaveOutEvent(); SoundOut.Init(SpeexProvider); SoundOut.Play(); }
private void callSpeak(Word word) { var path = (System.IO.Directory.GetParent(Environment.CurrentDirectory)).Parent.FullName; path = path + "/wav/" + word.tenfile; var wo = new NAudio.Wave.WaveOutEvent(); int vitribatdau = Convert.ToInt32(word.vitribatdau); int vitriketthuc = Convert.ToInt32(word.vitriketthuc); var reader = new StartEndLoopReader(new WaveFileReader(path), new TimeSpan(0, 0, vitribatdau), new TimeSpan(0, 0, vitriketthuc)); wo.Init(reader); wo.Play(); }
public void Play(string filePath) { try { if (!File.Exists(filePath)) throw new Exception(string.Format("No such a file:{0}!", filePath)); reader = new WaveFileReader(filePath); var waveOut = new WaveOutEvent(); waveOut.Init(reader); waveOut.PlaybackStopped += WaveOut_PlaybackStopped; ; waveOut.Play(); } catch(Exception exp) { Console.WriteLine(exp); } }
public static void PlayGameSound(GameSound sound) { var isSubscribed = SubscriptionModule.Get().IsSubscribed ?? false; if (isSubscribed && Prefs.EnableGameSound) { Log.InfoFormat("Playing game sound {0}", sound.Name); if (!sound.Src.ToLowerInvariant().EndsWith(".mp3")) { Log.InfoFormat("Playing game sound {0} as wav", sound.Name); PlaySound(sound.Src); return; } Task.Factory.StartNew(() => { try { Log.InfoFormat("Playing game sound {0} as mp3", sound.Name); using (var mp3Reader = new Mp3FileReader(sound.Src)) using (var stream = new WaveChannel32(mp3Reader) { PadWithZeroes = false }) using (var wo = new WaveOutEvent()) { Log.InfoFormat("Initializing game sound {0} as mp3", sound.Name); wo.Init(stream); wo.Play(); Log.InfoFormat("Waiting for game sound {0} to complete", sound.Name); var ttime = mp3Reader.TotalTime.Add(new TimeSpan(0,0,10)); var etime = DateTime.Now.Add(ttime.Add(new TimeSpan(0, 0, 10))); while (wo.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); if (DateTime.Now > etime) { break; } } Log.InfoFormat("Game sound {0} completed", sound.Name); } } catch (Exception e) { Log.Warn("PlayGameSound Error", e); } }); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var sine20Seconds = new SineWaveProvider(); using (var wo = new NAudio.Wave.WaveOutEvent()) { wo.Init(sine20Seconds); wo.Play(); while (wo.PlaybackState == PlaybackState.Playing) { sine20Seconds.Frequency = GetKeyFreq(); //uncomment code below to make frequency change over time // DateTime t = DateTime.Now; //long uT = ((DateTimeOffset)t).ToUnixTimeMilliseconds(); //sine20Seconds.Frequency = 500 + 400*Math.Sin(uT/1200.0); Console.WriteLine(" Freq: " + sine20Seconds.Frequency); Thread.Sleep(30); } } }
/// <summary> /// Creates the default AudioManager and starts the default outputs /// </summary> /// <param name="manager">The runmanager instance to use for this instance</param> public AudioManager(IRunManager manager) : base(manager) { //Init SynthGen MusicSynthOut = new WaveOutEvent(); MusicSynthGen = new SynthMusicProvider(manager); MusicSynthOut.Init(MusicSynthGen); //Init ExternalMusic MusicExternalOut = new WaveOutEvent(); MusicExternalProvider = new CustomMusicProvider(manager); MusicExternalOut.Init(MusicExternalProvider); //Enable default music provider switch (manager.Opts.Get<short>("snd_musicProvider")) { case 1: MusicExternal = true; break; case 2: MusicSynth = true; break; } }
public IWavePlayer PlaySFX(string sfxName) { IWavePlayer waveOutDevice = new WaveOutEvent(); var path = SFXPath + sfxName + ".mp3"; if (!File.Exists(path)) { RPGLog.Log("Did not find SFX to play"); return waveOutDevice; } AudioFileReader audioFileReader = new AudioFileReader(path); audioFileReader.Volume = Volume; waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); AudioDevices.Add(waveOutDevice); return waveOutDevice; }
public static void PlayGameSound(GameSound sound) { //var isSubscribed = SubscriptionModule.Get().IsSubscribed ?? false; //if (isSubscribed == false)return; if (Prefs.EnableGameSound == false) return; Log.InfoFormat("Playing game sound {0}", sound.Name); if (!sound.Src.ToLowerInvariant().EndsWith(".mp3")) { Log.InfoFormat("Playing game sound {0} as wav", sound.Name); PlaySound(sound.Src); return; } Task.Factory.StartNew(() => { try { Log.InfoFormat("Playing game sound {0} as mp3", sound.Name); var mp3Reader = new Mp3FileReader(sound.Src); var stream = new WaveChannel32(mp3Reader) { PadWithZeroes = false }; DisposeObjects.Add(mp3Reader); DisposeObjects.Add(stream); { stream.Position = 0; Mixer.AddMixerInput(stream); lock (Mixer) { if (WaveOut == null) { Log.Info("Starting up wave out"); WaveOut = new WaveOutEvent(); WaveOut.Init(new SampleToWaveProvider(Mixer)); WaveOut.PlaybackStopped += (sender, args) => { WaveOut.Dispose(); WaveOut = null; }; WaveOut.Play(); } } Log.InfoFormat("Initializing game sound {0} as mp3", sound.Name); } } catch (Exception e) { Log.Warn("PlayGameSound Error", e); Program.GameMess.Warning("Cannot play sound {0}, it must be in the format 44100:2", sound.Name); } }); }
private void InitializePlayer() { if (_player != null) { _player.Dispose(); } _player = new WaveOutEvent(); _player.Init(_currentPlaylistItem.Value); _canPlay = true; Application.Current.Dispatcher.Invoke(() => OnCanPlayChanged(new CanPlayEventArgs(_canPlay))); UpdateTotalTime(); }
public void PlaySound() { waveOutEvent.Init(sound); waveOutEvent.Play(); }
public VoiceCallCore() { UDPPort = new Random().Next(25050, 26050); Any = new IPEndPoint(IPAddress.Any, UDPPort); SoundOutProvider = new JitterBufferWaveProvider(); SoundOut = new WaveOutEvent(); SoundOut.Init(SoundOutProvider); SoundOut.Play(); try { SoundIn = new WaveInEvent(); SoundIn.WaveFormat = new WaveFormat(encoder.FrameSize * 50, 16, 1); SoundIn.DataAvailable += SoundIn_DataAvailable; SoundIn.BufferMilliseconds = 40; //SoundIn.StartRecording(); } catch { SoundInEnabled = false; } UdpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //UdpListener.SendTo(new byte[] { 0x0 }, new IPEndPoint(IPAddress.Broadcast, UDPPort)); UdpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); UdpListener.Bind(new IPEndPoint(IPAddress.Any, UDPPort)); UdpListener.BeginReceiveFrom(TmpBuffer, 0, 20480, SocketFlags.None, ref Any, DoReceiveFrom, null); }
// Used to set up the sound device private void InitialiseOutputDevice() { DisposeOutputDevice(); outputDevice = new WaveOutEvent(); //outputDevice.Init(new WaveChannel32(stream)); outputDevice.Init(PCMStream); }
private void playSound(Stream stream, CancellationToken token) { try { using(VorbisWaveReader vorbisStream = new VorbisWaveReader(stream)) { using(WaveOutEvent waveOut = new WaveOutEvent()) { waveOut.Init(vorbisStream); waveOut.Play(); while(waveOut.PlaybackState == PlaybackState.Playing) { if (token.IsCancellationRequested) break; Task.Delay(100, token); } } } } catch(TaskCanceledException) { } catch(OperationCanceledException) { } catch(Exception ex) { messenger.SendUi(new ApplicationErrorMessage { Exception = ex, HeaderText = "Error Playing Audio" }); } finally { stream.Close(); } }
private void pwfc_MouseUp(object sender, MouseButtonEventArgs e) { var file = new AudioFileReader(FileName); var trimmed = new OffsetSampleProvider(file); trimmed.SkipOver = pwfc.SelectionStart; trimmed.Take = TimeSpan.FromMilliseconds(Math.Abs(pwfc.SelectionEnd.TotalMilliseconds - pwfc.SelectionStart.TotalMilliseconds)); //WaveFileWriter.CreateWaveFile(@"c:\temp\trimmed.wav", new SampleToWaveProvider(trimmed)); new Task(() => { var player = new WaveOutEvent(); player.Init(trimmed); player.Play(); while (player.PlaybackState != PlaybackState.Stopped) { System.Threading.Thread.Sleep(100); } file.Close(); }).Start(); }
private void Button_Click(object sender, RoutedEventArgs e) { var file = new AudioFileReader(FileName); var trimmed = new OffsetSampleProvider(file); trimmed.SkipOver = pwfc.SelectionStart; trimmed.Take = pwfc.SelectionEnd - pwfc.SelectionStart; WaveFileWriter.CreateWaveFile(@"c:\temp\trimmed.wav", new SampleToWaveProvider(trimmed)); pwfc.ClearWaveForm(); FileName = @"c:\temp\trimmed.wav"; LoadSound(sound0, 0); var player = new WaveOutEvent(); player.Init(trimmed); player.Play(); }
public void PlayOnce() { Recalculate(); // TODO: Look into doing this properly (http://mark-dot-net.blogspot.de/2014/02/fire-and-forget-audio-playback-with.html) // Maybe do this with async? using (var output = new WaveOutEvent()) using (RawSourceWaveStream source = new RawSourceWaveStream(new MemoryStream(compressed), new WaveFormat(SampleRate, 1))) { output.Init(source); output.Play(); while (output.PlaybackState == PlaybackState.Playing) { Thread.Sleep(50); } } }
private void OnTimerElapsed(object sender, ElapsedEventArgs e) { if (_playbackState != StreamingPlaybackState.Stopped) { if (_waveOut == null && _bufferedWaveProvider != null) { _log.Log("Grooveshark: Initializing", Category.Info, Priority.Medium); try { _waveOut = new WaveOutEvent(); _volumeProvider = new VolumeWaveProvider16(_bufferedWaveProvider); _volumeProvider.Volume = Volume; _waveOut.Init(_volumeProvider); } catch (Exception ex) { _log.Log("Grooveshark: " + ex.ToString(), Category.Exception, Priority.High); _elapsedTimeSpan = TimeSpan.Zero; _playbackState = StreamingPlaybackState.Stopped; _timer.Stop(); _isPlaying(false); _trackComplete(_track); } } else if (_bufferedWaveProvider != null) { try { var bufferedSeconds = _bufferedWaveProvider.BufferedDuration.TotalSeconds; // make it stutter less if we buffer up a decent amount before playing if (bufferedSeconds < 0.5 && _playbackState == StreamingPlaybackState.Playing && !_fullyDownloaded) { _isBuffering(true); _log.Log("Grooveshark: Buffering..", Category.Info, Priority.Medium); _playbackState = StreamingPlaybackState.Buffering; if (_waveOut != null) { _waveOut.Pause(); _isPlaying(false); } } else if (bufferedSeconds > 4 && _playbackState == StreamingPlaybackState.Buffering) { _log.Log("Grooveshark: Buffering complete", Category.Info, Priority.Medium); if (_waveOut != null) { _waveOut.Play(); _playbackState = StreamingPlaybackState.Playing; _isPlaying(true); } _isBuffering(false); } else if (_fullyDownloaded && bufferedSeconds < 0.5) { _log.Log("Grooveshark: Buffer empty and the stream is fully downloaded. Complete..", Category.Info, Priority.Medium); _elapsedTimeSpan = TimeSpan.Zero; _isPlaying(false); _playbackState = StreamingPlaybackState.Stopped; _timer.Stop(); _trackComplete(_track); } } catch (Exception exception) { _log.Log(exception.ToString(), Category.Exception, Priority.Medium); } } if (_playbackState == StreamingPlaybackState.Playing) { _elapsedTimeSpan = _elapsedTimeSpan.Add(TimeSpan.FromMilliseconds(_timer.Interval)); _trackProgress(_track.TotalDuration.TotalMilliseconds, _elapsedTimeSpan.TotalMilliseconds); } } }
public IWavePlayer PlaySFX(string sfxName) { IWavePlayer waveOutDevice = new WaveOutEvent(); var path = SFXPath + sfxName + ".mp3"; AudioFileReader audioFileReader = new AudioFileReader(path); audioFileReader.Volume = Volume; waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); AudioDevices.Add(waveOutDevice); return waveOutDevice; }
public void OpenFile(string path) { Stop(); if (ActiveStream != null) { sampleReset = 0; SelectionBegin = TimeSpan.Zero; SelectionEnd = TimeSpan.Zero; ChannelPosition = 0; } StopAndCloseStream(); if (System.IO.File.Exists(path)) { try { waveOutDevice = new WaveOutEvent() { DesiredLatency = 100 }; this.inputStream = new AudioFileReaderRB(path); this.ActiveStream = this.inputStream.ReaderStream; sampleAggregator = new SampleAggregator(fftDataSize); Equalizer eq = new Equalizer(inputStream, this.bands); eq.Sample += eq_Sample; waveOutDevice.Init(eq); ChannelLength = inputStream.TotalTime.TotalSeconds; FileTag = TagLib.File.Create(path); //GenerateWaveformData(path); CanPlay = true; } catch { ActiveStream = null; CanPlay = false; } } }
private void GetAudioAsync(IAsyncResult res) { HttpWebRequest request = (HttpWebRequest)res.AsyncState; if (request == null) return; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(res); if (response == null) return; var waveFormat = WaveFormat.CreateMuLawFormat(8000, 1); Stream respStream = response.GetResponseStream(); var reader = new RawSourceWaveStream(respStream, waveFormat); using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)) { using (WaveOutEvent waveOut = new WaveOutEvent()) { waveOut.DeviceNumber = _audioDevices.GetCurWaveOutDeviceNumber(); waveOut.Init(convertedStream); while (true) { // Check if we should be stopping if (_reqToStop) { request.Abort(); _isListening = false; _reqToStop = false; logger.Info("ListenToAxisCamera::GetAudioAsync::Request aborted"); break; } // Play the audio waveOut.Play(); // Thread.Sleep(1); } } } /* * TEST CODE TO JUST SHOW STREAM READS - MUST COMMENT OUT ABOVE TO TRY * Stream r = response.GetResponseStream(); byte[] data = new byte[4096]; int read; while ((read = r.Read(data, 0, data.Length)) > 0) { Console.WriteLine(read); } */ }
public void Play(Track track, EndOfTrackCallbackDelegate endOfTrackCallbackDelegate) { endOfTrackCallback = endOfTrackCallbackDelegate; var avail = libspotify.sp_track_get_availability(SessionPtr, track.TrackPtr); if (avail != libspotify.sp_availability.SP_TRACK_AVAILABILITY_AVAILABLE) { _logger.ErrorFormat("Track is unavailable ({0}).", avail); if (endOfTrackCallback != null) { endOfTrackCallback(); } return; } _waveOutDevice.PlaybackStopped -= playbackStoppedHandler; var wasPlaying = _waveOutDevice.PlaybackState != PlaybackState.Paused; _waveOutDevice.Stop(); _waveOutDevice.Dispose(); _logger.InfoFormat("Playing track: {0} - {1}", track.Name, string.Join(",", track.Artists)); if (_spotify.TrackChanged != null) { _spotify.TrackChanged(track); } _waveOutDevice = new WaveOutEvent {DesiredLatency = 200}; _waveProvider.ClearBuffer(); _waveProvider.SetBufferFinished(false); _waveOutDevice.Init(_waveProvider); StartLoadingTrackAudio(track.TrackPtr); if (wasPlaying) { _waveOutDevice.Play(); } _waveOutDevice.PlaybackStopped += playbackStoppedHandler; }
public Session(SpotSharp spotify, byte[] appkey) { _spotify = spotify; _waveOutDevice = new WaveOutEvent { DesiredLatency = 200 }; playbackStoppedHandler = (sender, args) => { _logger.InfoFormat("Track Playback Stopped: {0}", args.Exception); if (endOfTrackCallback != null) { endOfTrackCallback(); } }; var callbacksPtr = AddCallbacks(); var config = new libspotify.sp_session_config { api_version = libspotify.SPOTIFY_API_VERSION, user_agent = "Spotbox", application_key_size = appkey.Length, application_key = Marshal.AllocHGlobal(appkey.Length), cache_location = Path.Combine(Path.GetTempPath(), "spotify_api_temp"), settings_location = Path.Combine(Path.GetTempPath(), "spotify_api_temp"), callbacks = callbacksPtr, compress_playlists = true, dont_save_metadata_for_playlists = false, initially_unload_playlists = false }; _logger.DebugFormat("api_version={0}", config.api_version); _logger.DebugFormat("application_key_size={0}", config.application_key_size); _logger.DebugFormat("cache_location={0}", config.cache_location); _logger.DebugFormat("settings_location={0}", config.settings_location); Marshal.Copy(appkey, 0, config.application_key, appkey.Length); IntPtr sessionPtr; var err = libspotify.sp_session_create(ref config, out sessionPtr); if (err != libspotify.sp_error.OK) { throw new ApplicationException(libspotify.sp_error_message(err)); } SessionPtr = sessionPtr; libspotify.sp_session_set_connection_type(sessionPtr, libspotify.sp_connection_type.SP_CONNECTION_TYPE_WIRED); _waveProvider = new HaltableBufferedWaveProvider(waveFormat); _waveOutDevice.Init(_waveProvider); _waveOutDevice.PlaybackStopped += playbackStoppedHandler; }
void playSound(String fileName) { var output = new WaveOutEvent(); try { var player = new WaveFileReader(fileName); output.Init(player); output.Play(); while (output.PlaybackState == PlaybackState.Playing && sounds.Count == 0) { Thread.Sleep(100); } output.Dispose(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
protected override void OnLoad(EventArgs e) { Visible = false; ShowInTaskbar = false; base.OnLoad(e); /* * Get all installed voices * */ var voices = speech.GetInstalledVoices(); string voice = ""; foreach (InstalledVoice v in voices) { if (v.Enabled) //voice = v.VoiceInfo.Name; Console.WriteLine(v.VoiceInfo.Name); } queuetimer = new System.Timers.Timer(250); queuetimer.Elapsed += (object sender, ElapsedEventArgs ev) => { TTSRequest r; if (Queue.TryDequeue(out r)) { Console.WriteLine("dequeing off of concurrent queue..."); if (r.Interrupt) { // stop current TTS if (IsSpeaking) { //speech.StopSpeaking(); } if (IsSounding) { //sound.Stop(); if(sound.PlaybackState == PlaybackState.Playing) { sound.Stop(); } } // clear queue SpeechQueue.Clear(); } if(!r.Reset) { SpeechQueue.Enqueue(r); } RequestCount++; } var eventdata = new Hashtable(); eventdata.Add("ProcessedRequests", RequestCount); eventdata.Add("QueuedRequests", SpeechQueue.Count); eventdata.Add("IsSpeaking", IsSounding); InstrumentationEvent blam = new InstrumentationEvent(); blam.EventName = "status"; blam.Data = eventdata; NotifyGui(blam.EventMessage()); }; // when this timer fires, it will pull off of the speech queue and speak it // the long delay also adds a little pause between tts requests. speechtimer = new System.Timers.Timer(250); speechtimer.Elapsed += (object sender, ElapsedEventArgs ev) => { if (IsSpeaking.Equals(false)) { if (SpeechQueue.Count > 0) { TTSRequest r = SpeechQueue.Dequeue(); Console.WriteLine("dequeuing off of speech queue"); IsSpeaking = true; speechtimer.Enabled = false; //speech.SpeakAsync(r.Text); //using (speech = new SpeechSynthesizer()) { speech = new SpeechSynthesizer(); speech.SpeakCompleted += speech_SpeakCompleted; format = new SpeechAudioFormatInfo(EncodingFormat.ALaw, 8000, 8, 1, 1, 2, null); //format = new SpeechAudioFormatInfo(11025, AudioBitsPerSample.Sixteen, AudioChannel.Mono); // var si = speech.GetType().GetMethod("SetOutputStream", BindingFlags.Instance | BindingFlags.NonPublic); stream = new MemoryStream(); //si.Invoke(speech, new object[] { stream, format, true, true }); //speech.SetOutputToWaveStream(stream); speech.SetOutputToAudioStream(stream, format); speech.SelectVoice(config.getVoice (r.Language, r.Voice)); int rate = (r.Speed * 2 - 10); Console.WriteLine(rate); try { speech.Rate = rate; } catch (ArgumentOutOfRangeException ex) { speech.Rate = 0; } speech.SpeakAsync(r.Text); //} synthesis.WaitOne(); speech.SpeakCompleted -= speech_SpeakCompleted; speech.SetOutputToNull(); speech.Dispose(); //IsSpeaking = false; IsSounding = true; stream.Position = 0; //WaveFormat.CreateCustomFormat(WaveFormatEncoding.WmaVoice9, 11025, 1, 16000, 2, 16) using(RawSourceWaveStream reader = new RawSourceWaveStream(stream, WaveFormat.CreateALawFormat(8000, 1))) { WaveStream ws = WaveFormatConversionStream.CreatePcmStream(reader); //var waveProvider = new MultiplexingWaveProvider(new IWaveProvider[] { ws }, 4); //waveProvider.ConnectInputToOutput(0, 3); sound = new WaveOutEvent(); // set output device *before* init Console.WriteLine("Output Device: " + OutputDeviceId); sound.DeviceNumber = OutputDeviceId; sound.Init(ws); //sound.Init(waveProvider); sound.PlaybackStopped += output_PlaybackStopped; // Console.WriteLine("playing here " + ws.Length); sound.Play(); } playback.WaitOne(); //IsSounding = false; speechtimer.Enabled = true; } } }; queuetimer.Enabled = true; queuetimer.Start(); speechtimer.Enabled = true; speechtimer.Start(); InitHTTPServer(); }
/// <summary> /// Plays a description, beginning from a time offset from the beginning of the wav file. /// </summary> /// <param name="description">Description to play.</param> /// <param name="offset">How far into the description to start playing at.</param> private void PlayAtOffset(Description description, double offset) { lock (_playLock) { var reader = new WaveFileReader(description.AudioFile); //reader.WaveFormat.AverageBytesPerSecond/ 1000 = Average Bytes Per Millisecond //AverageBytesPerMillisecond * (offset + StartWaveFileTime) = amount to play from reader.Seek((long)((reader.WaveFormat.AverageBytesPerSecond / 1000) * (offset + description.StartWaveFileTime)), SeekOrigin.Begin); var descriptionStream = new WaveOutEvent(); descriptionStream.PlaybackStopped += DescriptionStream_PlaybackStopped; descriptionStream.Init(reader); DescriptionStream = descriptionStream; _playingDescription = description; IsPlaying = true; _playingDescription.IsPlaying = true; descriptionStream.Play(); } }