Exemplo n.º 1
0
        private void Play(WaveStream stream, SpeakerState state)
        {
            // Stop all stream from playing for 1s
            if (DateTime.Now - StopTimeout < TimeSpan.FromMilliseconds(1000))
            {
                Log("Stop next speech");
                state.playing = false;
                stream.Dispose();
                return;
            }

            state.start = DateTime.Now;
            using (WaveChannel32 volume = new WaveChannel32(stream)) {
                volume.Volume = ConfigManager.GetInstance().Find("speaker.volume", 100) / 100f;
                waveOut.Init(volume);
                waveOut.Play();
                while (stream.CurrentTime < stream.TotalTime && (DateTime.Now - state.start) < state.timeout)
                {
                    Thread.Sleep(500);
                }
                waveOut.Stop();
                state.playing = false;
            }
            stream.Dispose();
        }
Exemplo n.º 2
0
        public int LoadWave(String fileName, bool needclose) // метод получения заголовка
        {
            StopPlayback();
            int result = 1;

            if (System.IO.File.Exists(fileName))
            {
                String extension = System.IO.Path.GetExtension(fileName).ToLower();                // получение пути к файлу

                switch (extension)                                                                 // чтение файла в зависимости от расширения
                {
                case ".mp3": reader = new NAudio.Wave.Mp3FileReader(fileName); result = 0; break;  // чтение mp3 файла

                case ".wav": reader = new NAudio.Wave.WaveFileReader(fileName); result = 0; break; // чтение wav файла

                default: break;
                }
            }
            if (reader != null)
            {
                waveFormat    = reader.WaveFormat.ToString();    // получение формата файла
                blockAlign    = reader.BlockAlign;               // получение размера блока выравнивания
                totalTime     = reader.TotalTime.TotalSeconds;   // получение длительности файла в секундах
                sampleRate    = reader.WaveFormat.SampleRate;    // получение частоты дискретизации
                bitsPerSample = reader.WaveFormat.BitsPerSample; // получение битового разрешения
                channels      = reader.WaveFormat.Channels;      // получение числа каналов

                if (needclose)
                {
                    reader.Close(); reader.Dispose();
                }                                                    // завершение чтение и освобождение памяти
            }
            return(result);
        }
Exemplo n.º 3
0
 void DestroyReader()
 {
     if (HasReader)
     {
         reader.Close(); reader.Dispose(); reader = null;
     }
 }
Exemplo n.º 4
0
        public void LoadFile(string fileName)
        {
            if (outStream != null)
            {
                outStream.Dispose();
            }

            if (fileName.EndsWith(".mp3"))
            {
                outStream = new Mp3FileReader(fileName);
            }
            else if (fileName.EndsWith(".wav"))
            {
                outStream = new WaveFileReader(fileName);
            }
            else
            {
                throw new InvalidOperationException("Can't open this type of file");
            }

            if (outStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
            {
                // no longer needed for MP3, but this should let us support mu-law etc
                outStream = WaveFormatConversionStream.CreatePcmStream(outStream);
            }
        }
 private void Play()
 {
     if (String.IsNullOrEmpty(InputPath))
     {
         MessageBox.Show("Select a valid input file or URL first");
         return;
     }
     if (wavePlayer == null)
     {
         CreatePlayer();
     }
     if (lastPlayed != inputPath && reader != null)
     {
         reader.Dispose();
         reader = null;
     }
     if (reader == null)
     {
         reader     = new MediaFoundationReader(inputPath);
         lastPlayed = inputPath;
         wavePlayer.Init(reader);
     }
     wavePlayer.Play();
     OnPropertyChanged("IsPlaying");
     OnPropertyChanged("IsStopped");
     timer.Start();
 }
Exemplo n.º 6
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }

                // Dispose stuff here
                if (Thimble != null)
                {
                    Thimble.Dispose();
                }

                if (outputDevice != null)
                {
                    outputDevice.Dispose();
                }

                if (audioReader != null)
                {
                    audioReader.Dispose();
                }

                if (audioDataStream != null)
                {
                    audioDataStream.Dispose();
                }
            }
            base.Dispose(disposing);
        }
Exemplo n.º 7
0
 private void OnDisposed(object sender, EventArgs eventArgs)
 {
     if (wavePlayer != null)
     {
         wavePlayer.Dispose();
         wavePlayer = null;
     }
     if (reader != null)
     {
         reader.Dispose();
         reader = null;
     }
 }
Exemplo n.º 8
0
        public void Stop()
        {
            if (waveOut != null)
            {
                waveOut.Stop();
                waveOut.Dispose();
                waveOut = null;
            }
            if (baStream != null)
            {
                baStream.Dispose();
                baStream = null;
            }
            if (wavStream != null)
            {
                wavStream.Dispose();
                wavStream = null;
            }

            if (mf != null)
            {
                mf.Close();
                mf.Dispose();
                mf = null;
            }
        }
Exemplo n.º 9
0
        static void PlayPCM(XAudio2 device, string fileName)
        {
            //WaveStream stream = new WaveStream(fileName);
            var s = System.IO.File.OpenRead(fileName);
            WaveStream stream = new WaveStream(s);
            s.Close();

            AudioBuffer buffer = new AudioBuffer();
            buffer.AudioData = stream;
            buffer.AudioBytes = (int)stream.Length;
            buffer.Flags = BufferFlags.EndOfStream;

            SourceVoice sourceVoice = new SourceVoice(device, stream.Format);
            sourceVoice.SubmitSourceBuffer(buffer);
            sourceVoice.Start();

            // loop until the sound is done playing
            while (sourceVoice.State.BuffersQueued > 0)
            {
                if (GetAsyncKeyState(VK_ESCAPE) != 0)
                    break;

                Thread.Sleep(10);
            }

            // wait until the escape key is released
            while (GetAsyncKeyState(VK_ESCAPE) != 0)
                Thread.Sleep(10);

            // cleanup the voice
            buffer.Dispose();
            sourceVoice.Dispose();
            stream.Dispose();
        }
Exemplo n.º 10
0
 private void CleanupPlayback()
 {
     if (wavePlayer != null)
     {
         lock (wavePlayer)
         {
             try
             {
                 if (wavePlayer != null)
                 {
                     wavePlayer.Dispose();
                     wavePlayer = null;
                 }
                 if (reader != null)
                 {
                     reader.Dispose();
                     reader = null;
                 }
             }
             catch {
                 if (Thread.CurrentThread.ThreadState == ThreadState.Running)
                 {
                     Thread.CurrentThread.Abort();
                 }
             }
         }
     }
 }
Exemplo n.º 11
0
 private void StopAndCloseStream()
 {
     if (waveOutDevice != null)
     {
         waveOutDevice.Stop();
         waveOutDevice.Dispose();
     }
     if (activeStream != null)
     {
         ActiveStream.Close();
         ActiveStream.Dispose();
         ActiveStream = null;
     }
     if (waveOutDevice != null)
     {
         waveOutDevice.Dispose();
         waveOutDevice = null;
     }
     if (inputStream != null)
     {
         inputStream.Close();
         inputStream.Dispose();
         inputStream = null;
     }
 }
Exemplo n.º 12
0
        private void StopAndCloseStream()
        {
            if (CanStop)
            {
                _waveOutDevice.Stop();
            }
            _currentFilePath = String.Empty;

            if (_inputStream != null)
            {
                _inputStream.Dispose();
                _inputStream = null;
            }

            if (_activeStream != null)
            {
                _activeStream.Dispose();
                _activeStream = null;
            }

            if (_waveOutDevice != null)
            {
                _waveOutDevice.Dispose();
                _waveOutDevice = null;
            }

            RefreshPlayingState();
        }
Exemplo n.º 13
0
 private void Dispose()
 {
     waveOut.Pause();
     waveOut.Dispose();
     blockAlignedStream.Close();
     blockAlignedStream.Dispose();
 }
Exemplo n.º 14
0
 private void CloseWaveOut()
 {
     stop();
     if (fileWaveStreamDAC != null)
     {
         // this one really closes the file and ACM conversion
         fileWaveStreamDAC.Dispose();
         _form.setVolumeDelegateDAC = null;
     }
     if (fileWaveStreamDefault != null)
     {
         // this one really closes the file and ACM conversion
         fileWaveStreamDefault.Dispose();
         _form.setVolumeDelegateDefault = null;
     }
     if (waveOutToMe != null)
     {
         waveOutToMe.Dispose();
         waveOutToMe = null;
     }
     if (waveOutToSkype != null)
     {
         waveOutToSkype.Dispose();
         waveOutToSkype = null;
     }
 }
Exemplo n.º 15
0
 private void CloseFile()
 {
     if (_fileStream == null)
         return;
     _fileStream.Dispose();
     _fileStream = null;
 }
Exemplo n.º 16
0
        private void cerrarToolStripMenu_Click(object sender, EventArgs e)
        {
            try
            {
                switch (currentFormat)
                {
                case ((sbyte)formats.wav): wove.Dispose(); break;

                case ((sbyte)formats.mp3): emp3.Dispose(); break;

                case ((sbyte)formats.ogg): vorb.Dispose(); break;
                }
                if (archivoActual != null)
                {
                    archivoActual.Dispose();
                }
            }
            catch { MessageBox.Show("Error Disposing invisible File\nthat or you got a random error.", "Data Still EXPUNGED"); }
            waveOut.Stop();
            waveOut.Dispose();
            audioView.Text       = "X_X";
            label_AudioData.Text = "[DATA EXPUNGED]";
            enabler_main(false);
            lastFormatOpened = 0;
        }
Exemplo n.º 17
0
        public void PlaySong()
        {
            if (playlist.Count < 1)
            {
                return;
            }

            if (player != null && player.PlaybackState != PlaybackState.Stopped)
            {
                player.Stop();
            }
            if (fileWaveStream != null)
            {
                fileWaveStream.Dispose();
            }
            if (player != null)
            {
                player.Dispose();
                player = null;
            }

            player         = new WaveOutEvent();
            fileWaveStream = new AudioFileReader(playlist.Dequeue());
            player.Init(fileWaveStream);
            player.PlaybackStopped += (sender, evn) => { PlaySong(); };
            player.Play();
        }
Exemplo n.º 18
0
        private void cerrarToolStripMenu_Click(object sender, EventArgs e)
        {
            try
            {
                switch (currentFormat)
                {
                case ((sbyte)formats.wav): wove.Dispose(); break;

                case ((sbyte)formats.mp3): emp3.Dispose(); break;

                case ((sbyte)formats.ogg): vorb.Dispose(); break;
                }
                if (archivoActual != null)
                {
                    archivoActual.Dispose();
                }
                trackUpdater.Stop();
                trackBar1.Value = 0;
            }
            catch { }
            waveOut.Stop();
            waveOut.Dispose();
            audioView.Text       = "X_X";
            label_AudioData.Text = "[DATA EXPUNGED]";
            enabler_main(false);
            lastFormatOpened = 0;
            label_Time.Text  = "Time: ";
        }
Exemplo n.º 19
0
        // ReSharper disable once UnusedParameter.Local
        private void PlayImpl(string soundName, double balance, double volume)
        {
            var soundStream = GetSoundStream(soundName);

            if (soundStream == null)
            {
                return;
            }

            var stream = new WaveStream(soundStream);
            var voice  = new SourceVoice(_audioDevice, stream.Format)
            {
                Volume = (float)volume
            };
            var buf = new AudioBuffer {
                AudioData = stream, AudioBytes = (int)stream.Length
            };

            voice.SubmitSourceBuffer(buf);
            voice.Start();

            // This does not work, need matrix http://xboxforums.create.msdn.com/forums/t/75836.aspx
            //voice.SetChannelVolumes(2, new[] {(float) (balance <= 0 ? 1 : balance), (float) (balance >= 0 ? 1 : -balance)});

            voice.BufferEnd += (sender, args) => _playerThreadDispatcher.BeginInvoke((Action)(() =>
            {
                voice.Stop();
                buf.Dispose();
                voice.Dispose();
                stream.Dispose();
            }));
        }
Exemplo n.º 20
0
 /// <summary>
 ///     Se encarga de comenzar a reproducir una cancion desde un archivo local
 /// </summary>
 /// <param name="ruta">La ruta de la cancion a reproducir</param>
 private void ReproducirCancionSinConexion(string ruta)
 {
     try
     {
         DetenerRecepcionDeCancion();
         _waveOutEvent.Stop();
         _bufferCancion      = new MemoryStream(File.ReadAllBytes(ruta));
         _mp3Reader          = new Mp3FileReader(_bufferCancion);
         _blockAlignedStream = new WaveChannel32(_mp3Reader);
         _waveOutEvent       = new WaveOut(WaveCallbackInfo.FunctionCallback());
         _waveOutEvent.Init(_blockAlignedStream);
         _estadoReproductor = EstadoReproductor.Reproduciendo;
         _seguidorDeEventosDelReproductor.Start();
         _waveOutEvent.Play();
     }
     catch (Exception ex)
     {
         new MensajeEmergente().MostrarMensajeError(ex.Message);
         _waveOutEvent.Stop();
         OnCambioEstadoReproduccion?.Invoke(false);
         _seguidorDeEventosDelReproductor.Stop();
         _estadoReproductor = EstadoReproductor.Detenido;
         if (_bufferCancion != null && _blockAlignedStream != null)
         {
             _bufferCancion.Dispose();
             _blockAlignedStream.Dispose();
         }
     }
 }
Exemplo n.º 21
0
 protected override void Play()
 {
     if (string.IsNullOrEmpty(InputPath) || File.Exists(InputPath) == false)
     {
         MessageBox.Show("Select a valid input file or URL first");
         return;
     }
     if (WavePlayer == null)
     {
         CreatePlayer();
     }
     if (_lastPlayed != InputPath && _reader != null)
     {
         _reader.Dispose();
         _reader = null;
     }
     if (_reader == null)
     {
         _reader        = new Mp3FileReader(InputPath);
         VolumeProvider = new VolumeWaveProvider16(_reader)
         {
             Volume = Volume / 100
         };
         _lastPlayed = InputPath;
         WavePlayer.Init(VolumeProvider);
         Duration = _reader.TotalTime;
     }
     WavePlayer.Play();
     UpdatePlayerState();
     PlayerTimer.Start();
     TaskbarOverlay = (ImageSource)Application.Current.FindResource("PlayImage");
     SetTitle("Playing " + Path.GetFileName(InputPath));
 }
Exemplo n.º 22
0
        static void PlayPCM(XAudio2 device, string fileName)
        {
            //WaveStream stream = new WaveStream(fileName);
            WaveStream stream;

            using (var s = System.IO.File.OpenRead(fileName))
            {
                stream = new WaveStream(s);
            }

            AudioBuffer buffer = new AudioBuffer();

            buffer.AudioData  = stream;
            buffer.AudioBytes = (int)stream.Length;
            buffer.Flags      = BufferFlags.EndOfStream;

            SourceVoice sourceVoice = new SourceVoice(device, stream.Format);

            sourceVoice.SubmitSourceBuffer(buffer);
            sourceVoice.Start();

            // loop until the sound is done playing
            while (sourceVoice.State.BuffersQueued > 0)
            {
                Thread.Sleep(10);
            }

            // cleanup the voice
            buffer.Dispose();
            sourceVoice.Dispose();
            stream.Dispose();
        }
Exemplo n.º 23
0
        public void PlaySound(string name, Action done = null)
        {
            FileStream ms        = File.OpenRead(_soundLibrary[name]);
            var        rdr       = new Mp3FileReader(ms);
            WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(rdr);
            var        baStream  = new BlockAlignReductionStream(wavStream);
            var        waveOut   = new WaveOut(WaveCallbackInfo.FunctionCallback());

            waveOut.Init(baStream);
            waveOut.Play();
            var bw = new BackgroundWorker();

            bw.DoWork += (s, o) =>
            {
                while (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    Thread.Sleep(100);
                }
                waveOut.Dispose();
                baStream.Dispose();
                wavStream.Dispose();
                rdr.Dispose();
                ms.Dispose();
                if (done != null)
                {
                    done();
                }
            };
            bw.RunWorkerAsync();
        }
Exemplo n.º 24
0
 private void CloseFile()
 {
     if (fileStream != null)
     {
         fileStream.Dispose();
         fileStream = null;
     }
 }
Exemplo n.º 25
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     if (disposing)
     {
         sourceStream.Dispose();
     }
 }
Exemplo n.º 26
0
 /// ------------------------------------------------------------------------------------
 private void CloseAndDisposeWaveStreamIfNeeded()
 {
     if (WaveStream != null)
     {
         WaveStream.Close();
         WaveStream.Dispose();
     }
 }
Exemplo n.º 27
0
 public void Dispose()
 {
     fileStream.Dispose();
     fileStream.Dispose();
     mp3FileReader.Dispose();
     wavStream.Dispose();
     baStream.Dispose();
     wave.Dispose();
 }
Exemplo n.º 28
0
        private void DisposeOldStreamAtKey(int position)
        {
            if (streams.ContainsKey(position))
            {
                WaveStream waveStream = streams[position];

                waveStream.Dispose();
            }
        }
Exemplo n.º 29
0
 protected override void Dispose(bool disposing)
 {
     if (disposing && readerStream != null)
     {
         readerStream.Dispose();
         readerStream = null;
     }
     base.Dispose(disposing);
 }
Exemplo n.º 30
0
 protected override void Dispose(bool disposing)
 {
     if (sourceStream != null)
     {
         sourceStream.Dispose();
         sourceStream = null;
     }
     base.Dispose(disposing);
 }
Exemplo n.º 31
0
 //If song is loaded, clean up
 public void Close()
 {
     if (ReturnSongLoaded() == true)
     {
         soundStream.Dispose();
         soundOut.Dispose();
         mp3Reader.Dispose();
     }
 }
Exemplo n.º 32
0
        public void Play( Form on )
        {
            var screens = Screen.AllScreens;
            var screens_left  = screens.Min( screen => screen.Bounds.Left  );
            var screens_right = screens.Max( screen => screen.Bounds.Right );
            var screens_width = screens_right-screens_left;

            var bestScreen = screens.OrderByDescending( screen => {
                var area = screen.Bounds;
                area.Intersect( on.Bounds );
                return area.Width*area.Height;
            }).First();

            var balances = new[]{1.5f,1.5f};
            if ( screens.Length==3 && DisplayBalances.ContainsKey(bestScreen.DeviceName) ) balances = DisplayBalances[bestScreen.DeviceName];

            var path   = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\.Default\"+Name+@"\.Current").GetValue(null) as string;
            var stream = new WaveStream(path);
            var buffer = new AudioBuffer() { AudioBytes=(int)stream.Length, AudioData=stream, Flags=BufferFlags.EndOfStream };

            var voice = new SourceVoice( XAudio2, stream.Format );
            voice.SubmitSourceBuffer( buffer );
            voice.SetChannelVolumes( balances.Length, balances );
            voice.BufferEnd += (sender,ctx) => {
                try {
                    on.BeginInvoke(new Action(()=>{
                        voice.Dispose();
                        buffer.Dispose();
                        stream.Dispose();
                    }));
                } catch ( InvalidOperationException ) {
                    // herp derp on must be disposed/gone
                }
            };
            voice.Start();
        }