Alternative WaveOut class, making use of the Event callback
Inheritance: IWavePlayer
Ejemplo n.º 1
1
        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();
        }
Ejemplo n.º 2
0
        public IWavePlayer CreateDevice(int latency)
        {
            IWavePlayer device;
            WaveCallbackStrategy strategy = _waveOutSettingsPanel.CallbackStrategy;
            if (strategy == WaveCallbackStrategy.Event)
            {
                WaveOutEvent waveOut = new WaveOutEvent
                {
                    DeviceNumber = _waveOutSettingsPanel.SelectedDeviceNumber,
                    DesiredLatency = latency
                };
                device = waveOut;
            }
            else
            {
                WaveCallbackInfo callbackInfo = strategy == WaveCallbackStrategy.NewWindow ? WaveCallbackInfo.NewWindow() : WaveCallbackInfo.FunctionCallback();
                WaveOut outputDevice = new WaveOut(callbackInfo)
                {
                    DeviceNumber = _waveOutSettingsPanel.SelectedDeviceNumber,
                    DesiredLatency = latency
                };
                device = outputDevice;
            }
            // TODO: configurable number of buffers

            return device;
        }
Ejemplo n.º 3
0
        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();
                        }

                    }
                }
            }
        }
Ejemplo n.º 4
0
        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 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);
        }
Ejemplo n.º 6
0
 static AudioPlayer()
 {
     var output = new WaveOutEvent();
     _mixer = new MixingSampleProvider(
         WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, ChannelCount));
     _mixer.ReadFully = true;
     output.Init(_mixer);
     output.Play();
 }
Ejemplo n.º 7
0
 // Start is called before the first frame update
 void Start()
 {
     waveOutEvent = new NAudio.Wave.WaveOutEvent();
     sound        = new NAudio.Wave.SampleProviders.SignalGenerator()
     {
         Gain      = 0.2,
         Frequency = 500,
         Type      = NAudio.Wave.SampleProviders.SignalGeneratorType.Sin
     }
     .Take(System.TimeSpan.FromSeconds(20));
 }
Ejemplo n.º 8
0
        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;
        }
Ejemplo n.º 9
0
        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();
        }
Ejemplo n.º 10
0
        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();
        }
Ejemplo n.º 11
0
 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);
     }
 }
Ejemplo n.º 12
0
        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);
                    }
                });
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Song"/> class.
        /// </summary>
        /// <param name="URI">The URI to be loaded.</param>
        /// <param name="_DeviceNumber">输出设备编号</param>\
        /// <param name="_Volume">声音大小</param>
        /// <param name="play">if set to <c>true</c> then the song will automatically play once loaded</param>
        public Song(string URI, int _DeviceNumber, float _Volume, bool play = false)
        {
            this.URI               = URI;
            this.provider          = MakeSong(this.URI);
            this.output            = new WaveOutEvent();
            output.DesiredLatency  = 300;
            output.NumberOfBuffers = 2;
            output.DeviceNumber    = _DeviceNumber;
            output.Volume          = _Volume;
            this.output.Init(provider);

            this.output.PlaybackStopped += output_PlaybackStopped;

            if (play)
            {
                this.Play();
            }
        }
Ejemplo n.º 14
0
        public Player Load(MediaFile song)
        {
            if (this.mp3 != null)
            {
                this.mp3.Close();
            }

            this.CurrentMediaFile = song;

            this.FindAlbumArt();

            this.mp3 = new Mp3FileReader(song.Path);
            this.TotalTime = this.mp3.TotalTime;

            var volumeStream = new WaveChannel32(mp3);
            this.player = new WaveOutEvent();
            this.player.PlaybackStopped += OnPlaybackStopped;
            this.player.Init(volumeStream);
            return this;
        }
Ejemplo n.º 15
0
        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);
                }
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (output != null)
             {
                 output.Stop();
                 output.Dispose();
                 output = null;
             }
             if (reduce != null)
             {
                 reduce.Dispose();
                 reduce = null;
             }
         }
         _disposed = true;
     }
 }
Ejemplo n.º 17
0
        /// <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;
            }
        }
Ejemplo n.º 18
0
        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;
        }
Ejemplo n.º 19
0
 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);
             }
         });
 }
Ejemplo n.º 20
0
 // Properly clean up sound output device
 public void DisposeOutputDevice()
 {
     if (outputDevice != null)
     {
         outputDevice.Stop();
         outputDevice.Dispose();
         outputDevice = null;
     }
 }
Ejemplo n.º 21
0
 public SoundPlayer()
 {
     //InitSoundThread();
     playbackDevice = new WaveOutEvent();
 }
        private IWavePlayer CreateDevice(int latency)
        {
            IWavePlayer device;

            var waveOut = new WaveOutEvent();
            waveOut.DeviceNumber = Settings.Default.AudioDeviceID;
            waveOut.DesiredLatency = latency;
            device = waveOut;

            return device;
        }
Ejemplo n.º 23
0
    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();
      }
    }
Ejemplo n.º 24
0
 public Player()
 {
     WaveOut = new WaveOutEvent();
 }
Ejemplo n.º 25
0
        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);
                        }
                        */
        }
Ejemplo n.º 26
0
 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());
     }
 }
Ejemplo n.º 27
0
        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;
        }
Ejemplo n.º 28
0
        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();
        }
Ejemplo n.º 29
0
        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;
        }
Ejemplo n.º 30
0
        // Used to set up the sound device
        private void InitialiseOutputDevice()
        {
            DisposeOutputDevice();

            outputDevice = new WaveOutEvent();
            //outputDevice.Init(new WaveChannel32(stream));
            outputDevice.Init(PCMStream);
        }
Ejemplo n.º 31
0
        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;
                }
            }
        }
Ejemplo n.º 32
0
        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);
        }
Ejemplo n.º 33
0
        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();

        }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Player"/> class.
 /// </summary>
 /// <param name="library">The library.</param>
 public Player(Library library)
 {
     waveOutDevice = new WaveOutEvent();
     this.library = library;
     waveOutDevice = new WaveOutEvent();
 }
Ejemplo n.º 35
0
        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();
        }
Ejemplo n.º 36
0
 private void Dispose(bool disposing)
 {
     if (wavStream != null)
     {
         wavStream.Dispose();
         wavStream = null;
     }
     if (playbackDevice != null)
     {
         playbackDevice.Stop();
         playbackDevice.Dispose();
         playbackDevice = null;
     }
 }