コード例 #1
0
ファイル: MainWindow.cs プロジェクト: yazici/AudioLab
        private void button1_Click(object sender, EventArgs e)
        {
            var ofn = new OpenFileDialog();

            ofn.Filter = CodecFactory.SupportedFilesFilterEN;
            if (ofn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Stop();

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    _soundOut = new WasapiOut();
                }
                else
                {
                    _soundOut = new DirectSoundOut();
                }

                var source = CodecFactory.Instance.GetCodec(ofn.FileName);
                source = new LoopStream(source)
                {
                    EnableLoop = false
                };
                (source as LoopStream).StreamFinished += (s, args) => Stop();

                _eq = Equalizer.Create10BandEqualizer(source);
                _soundOut.Initialize(_eq.ToWaveSource(16));
                _soundOut.Play();
            }
        }
コード例 #2
0
 public AudioPlayer(string audioFile)
 {
     AudioFile    = new DmoMp3Decoder(audioFile);
     OutputDevice = GetSoundOut();
     OutputDevice.Initialize(AudioFile);
     State = PlayerState.Paused;
 }
コード例 #3
0
        public bool SetAudioEndpoint(string dev, bool usedefault = false)
        {
            System.Collections.ObjectModel.ReadOnlyCollection <DirectSoundDevice> list = DirectSoundDeviceEnumerator.EnumerateDevices();

            DirectSoundDevice dsd = null;

            if (dev != null)                                               // active selection
            {
                dsd = list.FirstOrDefault(x => x.Description.Equals(dev)); // find

                if (dsd == null && !usedefault)                            // if not found, and don't use the default (used by constructor)
                {
                    return(false);
                }
            }

            DirectSoundOut dso = new DirectSoundOut(200, System.Threading.ThreadPriority.Highest); // seems good quality at 200 ms latency

            if (dso == null)                                                                       // if no DSO, fail..
            {
                return(false);
            }

            if (dsd != null)
            {
                dso.Device = dsd.Guid;
            }
            else
            {
                DirectSoundDevice def = DirectSoundDevice.DefaultDevice;
                dso.Device = def.Guid;  // use default GUID
            }

            NullWaveSource nullw = new NullWaveSource(10);

            try
            {
                dso.Initialize(nullw);  // check it takes it.. may not if no sound devices there..
                dso.Stop();
                nullw.Dispose();
            }
            catch
            {
                nullw.Dispose();
                dso.Dispose();
                return(false);
            }

            if (aout != null)                 // clean up last
            {
                aout.Stopped -= Output_Stopped;
                aout.Stop();
                aout.Dispose();
            }

            aout          = dso;
            aout.Stopped += Output_Stopped;

            return(true);
        }
コード例 #4
0
ファイル: MusicPlayer.cs プロジェクト: week9/Switch-Toolbox
        public void Open(string filename, MMDevice device)
        {
            CleanupPlayback();

            _waveSource =
                CodecFactory.Instance.GetCodec(filename)
                .ToSampleSource()
                .ToMono()
                .ToWaveSource();

            _sampleSource = _waveSource.ToSampleSource()
                            .AppendSource(x => new PitchShifter(x), out _pitchShifter);

            SetupSampleSource(_sampleSource);

            _soundOut = new WasapiOut()
            {
                Latency = 100, Device = device
            };
            _soundOut.Initialize(_waveSource);
            if (PlaybackStopped != null)
            {
                _soundOut.Stopped += PlaybackStopped;
            }
        }
コード例 #5
0
ファイル: CSCorePlayer.cs プロジェクト: candyzkn/Dopamine
        private void InitializeSoundOut(IWaveSource soundSource)
        {
            // Create SoundOut
            this.soundOut = new WasapiOut(this.eventSync, this.audioClientShareMode, this.latency, ThreadPriority.Highest);

            if (this.outputDevice == null)
            {
                // If no output device was provided, we're playing on the default device.
                // In such case, we want to detected when the default device changes.
                // This is done by setting stream routing options
                ((WasapiOut)this.soundOut).StreamRoutingOptions = StreamRoutingOptions.All;
            }
            else
            {
                // If an output device was provided, assign it to soundOut.Device.
                // Only allow stream routing when the device was disconnected.
                ((WasapiOut)this.soundOut).StreamRoutingOptions = StreamRoutingOptions.OnDeviceDisconnect;
                ((WasapiOut)this.soundOut).Device = this.outputDevice;
            }

            // Initialize SoundOut
            this.notificationSource = new SingleBlockNotificationStream(soundSource.ToSampleSource());
            this.soundOut.Initialize(this.notificationSource.ToWaveSource(16));

            if (inputStreamList.Count != 0)
            {
                foreach (var inputStream in inputStreamList)
                {
                    this.notificationSource.SingleBlockRead += inputStream;
                }
            }

            this.soundOut.Stopped += this.SoundOutStoppedHandler;
            this.soundOut.Volume   = this.volume;
        }
コード例 #6
0
        public void Open(IAudioFile file)
        {
            StopPlayback();
            _soundSource?.Dispose();
            _simpleNotificationSource?.Dispose();

            _currentMemoryStream = new MemoryStream(file.Data);
            _soundSource         =
                new DmoMp3Decoder(_currentMemoryStream).AppendSource(
                    x => new SimpleNotificationSource(x.ToSampleSource()),
                    out _simpleNotificationSource).ToWaveSource();
            _simpleNotificationSource.BlockRead += SimpleNotificationSource_BlockRead;

            if (_soundOut == null)
            {
                _soundOut          = new WasapiOut();
                _soundOut.Stopped += SoundOut_Stopped;
            }

            _soundOut.Initialize(_soundSource);
            _soundOut.Volume = Volume;

            OnTrackLengthChanged();
            TrackPosition = 0;
            OnPositionChanged();
        }
コード例 #7
0
ファイル: PlayerModule.cs プロジェクト: waynejhou/LRCEditor
        public void Open(string filename)
        {
            CleanupPlayback();

            _waveSource =
                CodecFactory.Instance.GetCodec(filename)
                .ToSampleSource()
                .ToStereo()
                .ToWaveSource();
            _soundOut = new WasapiOut()
            {
                Latency = 100
            };
            _soundOut.Initialize(_waveSource);
            _soundOut.Volume = Math.Min(1.0f, Math.Max((float)volumeHandle / 100f, 0f));
            if (PlaybackStopped != null)
            {
                _soundOut.Stopped += PlaybackStopped;
            }

            PositionUpdateThread = new Thread(() => {
                while (true)
                {
                    PositionChangedEvent?.Invoke(this);
                    Thread.Sleep(10);
                }
            });
            PositionUpdateThread.Start();
        }
コード例 #8
0
        public void Open(string filename)
        {
            CleanupPlayback();

            //open the selected file
            _waveSource = CodecFactory.Instance.GetCodec(filename)
                          .ToSampleSource()
                          .ToMono()
                          .ToWaveSource();

            if (WasapiOut.IsSupportedOnCurrentPlatform)
            {
                _soundOut = new WasapiOut {
                    Latency = 100
                }
            }
            ;
            else
            {
                _soundOut = new DirectSoundOut {
                    Latency = 100
                }
            };

            _soundOut.Initialize(_waveSource);

            if (PlaybackStopped != null)
            {
                _soundOut.Stopped += PlaybackStopped;
            }
        }
コード例 #9
0
        public void CargarCancion(string cual)
        {
            switch (Path.GetExtension(cual))
            {
            case ".mp3":
                FormatoSonido = FormatoSonido.MP3;
                break;

            case ".flac":
                FormatoSonido = FormatoSonido.FLAC;
                break;

            case ".ogg":
                FormatoSonido = FormatoSonido.OGG;
                break;

            default:
                break;
            }
            try
            {
                Log.Instance.PrintMessage("Intentando cargar " + cual, MessageType.Info);
                if (Path.GetExtension(cual) == ".ogg")
                {
                    FileStream stream = new FileStream(cual, FileMode.Open, FileAccess.Read);
                    NVorbis = new NVorbisSource(stream);
                    _sound  = NVorbis.ToWaveSource(16);
                }
                else
                {
                    _sound             = CSCore.Codecs.CodecFactory.Instance.GetCodec(cual).ToSampleSource().ToStereo().ToWaveSource(16);
                    notificationStream = new SingleBlockNotificationStream(_sound.ToSampleSource());
                    FileInfo info = new FileInfo(cual);
                    tamFich = info.Length;
                }

                _output = new WasapiOut(false, AudioClientShareMode.Shared, 100);
                //_sonido.Position = 0;
                _output.Initialize(_sound);
                Log.Instance.PrintMessage("Cargado correctamente" + cual, MessageType.Correct);
            }
            catch (IOException ex)
            {
                Log.Instance.PrintMessage("Error de IO", MessageType.Error);
                Log.Instance.PrintMessage(ex.Message, MessageType.Error);
                Kernel.ShowError(Kernel.LocalTexts.GetString("errorReproduccion"));
                _output = null;
                _sound  = null;
                throw;
            }
            catch (Exception ex)
            {
                Log.Instance.PrintMessage("Hubo un problema...", MessageType.Error);
                Log.Instance.PrintMessage(ex.Message, MessageType.Error);
                Kernel.ShowError(ex.Message);
                _output = null;
                _sound  = null;
                throw;
            }
        }
コード例 #10
0
ファイル: MainWindow.cs プロジェクト: CheViana/AudioLab
        private void button1_Click(object sender, EventArgs e)
        {
            var ofn = new OpenFileDialog();
            ofn.Filter = CodecFactory.SupportedFilesFilterEN;
            if (ofn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Stop();

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    _soundOut = new WasapiOut();
                }
                else
                {
                    _soundOut = new DirectSoundOut();
                }

                var source = CodecFactory.Instance.GetCodec(ofn.FileName);
                source = new LoopStream(source) { EnableLoop = false };
                (source as LoopStream).StreamFinished += (s, args) => Stop();

                _eq = Equalizer.Create10BandEqualizer(source);
                _soundOut.Initialize(_eq.ToWaveSource(16));
                _soundOut.Play();
            }
        }
コード例 #11
0
        private void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (isDisposing)
            {
                StopHandler();

                if (_updateTimer != null)
                {
                    _updateTimer.Stop();
                    _updateTimer = null;
                }

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

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

            _isDisposed = true;
        }
コード例 #12
0
        public bool SetAudioEndpoint(string dev, bool usedefault = false)
        {
            System.Collections.ObjectModel.ReadOnlyCollection <DirectSoundDevice> list = DirectSoundDeviceEnumerator.EnumerateDevices();

            DirectSoundDevice dsd = null;

            if (dev != null)                                               // active selection
            {
                dsd = list.FirstOrDefault(x => x.Description.Equals(dev)); // find
                if (dsd == null && !usedefault)                            // if not found, and don't use the default (used by constructor)
                {
                    return(false);
                }
            }

            DirectSoundOut dso = new DirectSoundOut(200);    // seems good quality at 200 ms latency

            if (dsd != null)
            {
                dso.Device = dsd.Guid;
            }

            if (aout != null)                   // clean up last
            {
                aout.Stopped -= Output_Stopped;
                aout.Stop();
                aout.Dispose();
            }

            aout          = dso;
            aout.Stopped += Output_Stopped;

            return(true);
        }
コード例 #13
0
ファイル: SpeechService.cs プロジェクト: gqgunhed/EDDI
        private void StartSpeech(ref ISoundOut soundout, int priority)
        {
            bool started = false;

            while (!started)
            {
                if (activeSpeech == null)
                {
                    lock (activeSpeechLock)
                    {
                        Logging.Debug("Checking to see if we can start speech");
                        if (activeSpeech == null)
                        {
                            Logging.Debug("We can - setting active speech");
                            activeSpeech         = soundout;
                            activeSpeechPriority = priority;
                            started = true;
                            Logging.Debug("Playing sound buffer");
                            soundout.Play();
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }
コード例 #14
0
ファイル: Audio.cs プロジェクト: CarimA/GbJam8
        public void PlayBgm(string song, bool resolvedName = false)
        {
            CleanupPlayback();

            var filename = resolvedName
                ? song
                : $"{AppContext.BaseDirectory}/assets/bgm/{song}.ogg";

            _musicSource =
                CodecFactory.Instance.GetCodec(filename)
                .ChangeSampleRate(11025)
                .ToSampleSource()
                .ToMono()
                .ToWaveSource();
            _musicOut = new WasapiOut {
                Latency = 100
            };
            _musicOut.Initialize(_musicSource);

            if (PlaybackStopped != null)
            {
                _musicOut.Stopped += PlaybackStopped;
            }

            _musicOut?.Play();
        }
コード例 #15
0
        public void Dispose()
        {
            if (aout != null)
            {
                aout.Stop();

                try
                {
                    aout.Dispose();
                }
                catch (DirectSoundException ex)
                {
                    if (ex.Result == DSResult.BufferLost)
                    {
                        System.Diagnostics.Trace.WriteLine($"Audio object disposal failed with DSERR_BUFFERLOST - continuing\n{ex.ToString()}");
                    }
                    else
                    {
                        throw;
                    }
                }

                aout = null;
            }
        }
コード例 #16
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Filter = CodecFactory.SupportedFilesFilterEn,
                Title  = "Select a file..."
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stop();

                //open the selected file
                ISampleSource source = CodecFactory.Instance.GetCodec(openFileDialog.FileName)
                                       .ToSampleSource()
                                       .AppendSource(x => new PitchShifter(x), out _pitchShifter);

                SetupSampleSource(source);

                //play the audio
                _soundOut = new WasapiOut();
                _soundOut.Initialize(_source);
                _soundOut.Play();

                timer1.Start();

                propertyGridTop.SelectedObject    = _lineSpectrum;
                propertyGridBottom.SelectedObject = _voicePrint3DSpectrum;
            }
        }
コード例 #17
0
ファイル: SoundBoard.cs プロジェクト: DopeDealers/SoundBoard
        private void PlaySoundFile(object filename)
        {
            using (IWaveSource soundSource = CodecFactory.Instance.GetCodec(filename as string))
            {
                //SoundOut implementation which plays the sound
                using (soundOut = GetSoundOut())
                {
                    //Tell the SoundOut which sound it has to play
                    soundOut.Initialize(soundSource);

                    //Play the sound
                    soundOut.Play();

                    while (soundOut.PlaybackState == PlaybackState.Playing)
                    {
                        Thread.Sleep(500);
                    }

                    //Stop the playback
                    if (soundOut.PlaybackState != PlaybackState.Stopped)
                    {
                        soundOut.Stop();
                    }
                    OnPlaybackStop(this, null);
                }
            }
        }
コード例 #18
0
        protected internal override SoundEffectData CreateSoundEffect(string file)
        {
            IWaveSource source   = CodecFactory.Instance.GetCodec(file);
            ISoundOut   soundOut = this.CreateSoundOut(ref source);

            return(new CsCoreData(soundOut, source));
        }
コード例 #19
0
ファイル: CSCorePlayer.cs プロジェクト: ptddqr/Dopamine
        private void InitializeSoundOut(IWaveSource soundSource, MMDevice outputDevice)
        {
            // SoundOut implementation which plays the sound
            this.soundOut = new WasapiOut(this.eventSync, this.audioClientShareMode, this.latency, ThreadPriority.Highest)
            {
                Device = outputDevice
            };
            ((WasapiOut)this.soundOut).StreamRoutingOptions = StreamRoutingOptions.All;

            // Initialize the soundOut
            this.notificationSource = new SingleBlockNotificationStream(soundSource.ToSampleSource());
            this.soundOut.Initialize(this.notificationSource.ToWaveSource(16));

            if (inputStreamList.Count != 0)
            {
                foreach (var inputStream in inputStreamList)
                {
                    this.notificationSource.SingleBlockRead += inputStream;
                }
            }

            this.soundOut.Stopped += this.SoundOutStoppedHandler;

            this.soundOut.Volume = this.volume;
        }
コード例 #20
0
        private void PlaybackStoppedEventTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < basic_iteration_count; i++)
            {
                bool raised = false;
                soundOut.Stopped += (s, e) => raised = true;

                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep((int)(source.GetLength().TotalMilliseconds + 50));
                while (soundOut.PlaybackState != PlaybackState.Stopped)
                {
                    ;
                }

                soundOut.Initialize(source); //the playbackstate may be stopped but event was not fired. initialize will wait until it gets fired.

                source.Position = 0;
                Assert.IsTrue(raised);
                raised = false; //check for event on eof

                soundOut.Play();

                Thread.Sleep(50);
                soundOut.Stop();

                Assert.IsTrue(raised);
            }
        }
コード例 #21
0
 public CSCoreSoundEffect(string filePath, string name)
     : base(filePath, name)
 {
     _waveSource    = CodecFactory.Instance.GetCodec(filePath);
     _instances     = new ISoundOut[_maxInstances];
     _instanceIndex = 0;
 }
コード例 #22
0
        public void OpenFile(string fileName)
        {
            //open the selected file
            var waveSource = CodecFactory.Instance.GetCodec(fileName)
                             .ToSampleSource()
                             .AppendSource(x => new PitchShifter(x), out _pitchShifter);

            SetupSampleSource(waveSource);

            //play the audio
            if (WasapiOut.IsSupportedOnCurrentPlatform)
            {
                _soundOut = new WasapiOut();
            }
            else
            {
                _soundOut = new DirectSoundOut();
            }

            _soundOut.Initialize(_source);
            _soundOut.Play();

            timer1.Start();

            propertyGridTop.SelectedObject = _lineSpectrum;
        }
コード例 #23
0
ファイル: CSCorePlayer.cs プロジェクト: kbalint/Dopamine
        private void CloseSoundOut()
        {
            this.CloseNotificationClient(); // Prevents a NullReferenceException in CSCore

            if (this.soundOut != null)
            {
                try
                {
                    // Remove the handler because we don't want to trigger this.soundOut.Stopped()
                    // when manually stopping the player. That event should only be triggered
                    // when CSCore reaches the end of the Track by itself.
                    this.soundOut.Stopped -= this.SoundOutStoppedHandler;
                    this.soundOut.Stop();

                    if (this.soundOut.WaveSource != null)
                    {
                        this.soundOut.WaveSource.Dispose();
                    }
                    if (this.equalizer != null)
                    {
                        this.equalizer.Dispose();
                    }

                    this.soundOut.Dispose();
                    this.soundOut = null;
                }
                catch (Exception)
                {
                    //Swallow
                }
            }
        }
コード例 #24
0
        /// <summary>
        ///     Blocks the current thread until the playback of the specified <paramref name="soundOut"/> instance stops or the specified timeout expires.
        /// </summary>
        /// <param name="soundOut">The <see cref="ISoundOut"/> instance to wait for its playback to stop.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait. Pass <see cref="Timeout.Infinite"/> to wait indefinitely.</param>
        /// <returns><c>true</c> if the <paramref name="soundOut"/> got stopped; <c>false</c> if the specified <paramref name="millisecondsTimeout"/> expired.</returns>
        public static bool WaitForStopped(this ISoundOut soundOut, int millisecondsTimeout)
        {
            if (soundOut == null)
            {
                throw new ArgumentNullException("soundOut");
            }
            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout");
            }

            if (soundOut.PlaybackState == PlaybackState.Stopped)
            {
                return(true);
            }

            using (var waitHandle = new AutoResetEvent(false))
            {
                EventHandler <PlaybackStoppedEventArgs> handler = (s, e) => waitHandle.Set();
                soundOut.Stopped += handler;
                bool result = waitHandle.WaitOne(millisecondsTimeout);
                // need to unsubscrive because waitHandle will be disposed
                soundOut.Stopped -= handler;
                return(result);
            }
        }
コード例 #25
0
 void Play()
 {
     if (soundOut == null || soundOut.PlaybackState == PlaybackState.Stopped)
     {
         MakeLabels(listView1.Items[now].SubItems[2].Text);
         soundSource = SoundSource(listView1.Items[now].SubItems[2].Text);
         var source = soundSource
                      .ChangeSampleRate(32000)
                      .ToSampleSource()
                      .AppendSource(Equalizer.Create10BandEqualizer, out equalizer)
                      .ToWaveSource();
         soundOut = SoundOut();
         soundOut.Initialize(source);
         float vol = tbar_volume.Value * 0.1f;
         soundOut.Volume = vol;
         soundOut.Play();
         Play_Aux();
         listView1.Items[now].BackColor = Color.SkyBlue;
         listView1.Items[now].ForeColor = Color.DarkSlateGray;
         soundOut.Stopped += Play_Aux_2;
     }
     else if (soundOut.PlaybackState == PlaybackState.Paused)
     {
         soundOut.Resume();
         timer_ctime.Enabled = true;
     }
     btn_Play.Visible  = false;
     btn_pause.Visible = true;
 }
コード例 #26
0
ファイル: MainWindow.cs プロジェクト: nikkei00/LessonBell63
        private void button1_Click(object sender, EventArgs e)
        {
            var ofn = new OpenFileDialog();

            ofn.Filter = CodecFactory.SupportedFilesFilterEn;
            if (ofn.ShowDialog() == DialogResult.OK)
            {
                Stop();

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    _soundOut = new WasapiOut();
                }
                else
                {
                    _soundOut = new DirectSoundOut();
                }

                var source = CodecFactory.Instance.GetCodec(ofn.FileName)
                             .Loop()
                             .ChangeSampleRate(32000)
                             .ToSampleSource()
                             .AppendSource(Equalizer.Create10BandEqualizer, out _equalizer)
                             .ToWaveSource();

                _soundOut.Initialize(source);
                _soundOut.Play();
            }
        }
コード例 #27
0
        private void StopCSCore()
        {
            if (_soundOut != null)
            {
                _soundOut.Stop();
                _soundOut.Dispose();
                _soundOut = null;
            }
            if (_soundIn != null)
            {
                _soundIn.Stop();
                _soundIn.Dispose();
                _soundIn = null;
            }
            if (_source != null)
            {
                _source.Dispose();
                _source = null;
            }

            if (_lineSpectrum != null)
            {
                _lineSpectrum = null;
            }
        }
コード例 #28
0
        private void PlayStopTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < basic_iteration_count; i++)
            {
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();

                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();

                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
            }
        }
コード例 #29
0
ファイル: MusicPlayer.cs プロジェクト: APlagman/PacSharp
        public void Open(string filename, MMDevice device, bool loop)
        {
            CleanupPlayback();

            waveSource =
                CodecFactory.Instance.GetCodec(filename)
                .ToSampleSource()
                .ToMono()
                .ToWaveSource();
            if (loop)
            {
                waveSource = new LoopStream(waveSource);
            }
            else
            {
                waveSource = new CachedSoundSource(waveSource);
            }
            soundOut = new WasapiOut()
            {
                Latency = 100, Device = device
            };
            soundOut.Initialize(waveSource);
            if (PlaybackStopped != null)
            {
                soundOut.Stopped += PlaybackStopped;
            }
        }
コード例 #30
0
        private void CloseSoundOut()
        {
            if (this.soundOut != null)
            {
                try
                {
                    if (this.notificationSource != null)
                    {
                        this.notificationSource.SingleBlockRead -= this.InputStream_Sample;
                    }

                    // Remove the handler because we don't want to trigger this.soundOut.Stopped()
                    // when manually stopping the player. That event should only be triggered
                    // when CSCore reaches the end of the Track by itself.
                    this.soundOut.Stopped -= this.SoundOutStoppedHandler;
                    this.soundOut.Stop();

                    if (this.soundOut.WaveSource != null)
                    {
                        this.soundOut.WaveSource.Dispose();
                    }
                    if (this.equalizer != null)
                    {
                        this.equalizer.Dispose();
                    }

                    this.soundOut.Dispose();
                    this.soundOut = null;
                }
                catch (Exception)
                {
                    //Swallow
                }
            }
        }
コード例 #31
0
        private void Init()
        {
            this.Dispose();

            this.soundSource = new SilenceSource();
            this.soundOut    = new DirectSoundOut();
            this.soundOut.Initialize(this.soundSource);
        }
コード例 #32
0
ファイル: CsCoreData.cs プロジェクト: Artentus/GameUtils
        internal CsCoreData(ISoundOut soundOut, IWaveSource source)
        {
            this.soundOut = soundOut;
            this.source = source;
            locker = new object();

            soundOut.Initialize(source);
        }
コード例 #33
0
ファイル: FadingService.cs プロジェクト: caesay/Hurricane
        /// <summary>
        /// Fade the soundOut slowly out
        /// </summary>
        /// <param name="soundOut">The sound out from CSCore</param>
        /// <param name="fromVolume">The final volume</param>
        /// <returns></returns>
        public async Task FadeOut(ISoundOut soundOut, float fromVolume)
        {
            if (IsFading && !_cancellationToken.IsCancellationRequested)
                return;

            IsFading = true;
            await Fade(fromVolume, 0, TimeSpan.FromMilliseconds(Duration), soundOut, _cancellationToken.Token);
            IsFading = false;
        }
コード例 #34
0
ファイル: MainWindow.cs プロジェクト: CheViana/AudioLab
 private void Stop()
 {
     if (_soundOut != null)
     {
         _soundOut.Stop();
         _soundOut.Dispose();
         _eq.Dispose();
         _soundOut = null;
     }
 }
コード例 #35
0
ファイル: Form1.cs プロジェクト: Jakub-jk/Songer-OLD-
        public Form1()
        {
            //MetroMessageBox.Show(this, string.Format("{0} - 1, {1} - 2, {2} - 3", StylesList[1], StylesList[2], StylesList[3]));
            InitializeComponent();

            #region Player Initialization
            player = GetSoundOut();
            playerInit = true;
            player.Stopped += new EventHandler<PlaybackStoppedEventArgs>(player_Stopped);
            #endregion

            LoadFromSettings();

            #region Settings Initialization
            for (int i = 1; i < Enum.GetNames(typeof(MetroColorStyle)).Length; i++)
                mcbStyles.Items.Add(StylesList[i]);
            mcbThemes.Items.Add(ThemesList[1]);
            mcbThemes.Items.Add(ThemesList[2]);
            mcbThemes.SelectedItem = msm.Theme;
            mcbStyles.SelectedItem = msm.Style;
            #endregion

            #region Taskbar Buttons Add & Delegates
            ttbbPlayPause.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbPlayPause_Click);
            ttbbNext.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbNext_Click);
            ttbbPrev.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbPrev_Click);
            ttbbForward.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbForward_Click);
            ttbbRewind.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbRewind_Click);

            TaskbarManager.Instance.ThumbnailToolBars.AddButtons(this.Handle, ttbbPrev, ttbbRewind, ttbbPlayPause, ttbbForward, ttbbNext);
            #endregion

            #region Song Initialization
            foreach (FileInfo fi in (new DirectoryInfo(Path.GetFullPath("TestMusic")).GetFiles()))
                Playlist.Add(fi.FullName);
            //TODO: MAKE IT WORKING!
            /*System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
            pfc.AddFontFile(Path.GetFullPath("comfortaa.ttf"));
            Font = new Font(pfc.Families[0], Font.Size, Font.Style);
            foreach (Control c in Controls)
                c.Font = new Font(pfc.Families[0],c.Font.Size, c.Font.Style);*/
            GetAndFillWithSongInfo();

            source = CodecFactory.Instance.GetCodec(Playlist[ActualFileIndex]);
            ActualFileIndex = 0;
            player.Initialize(source);
            player.Play();
            mtbTime.Maximum = Convert.ToInt32(source.GetLength().TotalSeconds);
            mtbTime.Value = 0;
            t.Tick += new EventHandler(Tick);
            t.Start();
            #endregion

            //AddTrackToList(Playlist[0], Playlist[1]);
        }
コード例 #36
0
ファイル: FadingService.cs プロジェクト: caesay/Hurricane
        /// <summary>
        /// Fade the soundOut slowly out and disposes it after that
        /// </summary>
        /// <param name="soundOut">The sound out from CSCore</param>
        /// <param name="duration">The duration</param>
        /// <returns></returns>
        public async Task CrossfadeOut(ISoundOut soundOut, TimeSpan duration)
        {
            if (IsFading && !_cancellationToken.IsCancellationRequested)
                return;

            IsFading = true;
            await Fade(soundOut.Volume, 0, duration, soundOut, _cancellationToken.Token);
            IsFading = false;
            if (soundOut.PlaybackState != PlaybackState.Stopped)
                soundOut.Stop();
            using (soundOut) 
                soundOut.WaveSource.Dispose();
        }
コード例 #37
0
ファイル: CSCoreEngine.cs プロジェクト: caesay/Hurricane
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // free managed resources
         if (_fadingService.IsFading)
             _fadingService.Cancel();
         StopPlayback();
         _soundOut?.Dispose();
         _soundOut = null;
         _soundSource?.Dispose();
         SoundOutProvider.Dispose();
         _loopStream?.Dispose();
         _equalizer?.Dispose();
         _simpleNotificationSource?.Dispose();
         _soundSourceLoadingToken?.Dispose();
     }
     // free native resources if there are any.
 }
コード例 #38
0
ファイル: FadingService.cs プロジェクト: caesay/Hurricane
        private async static Task Fade(float volumeFrom, float volumeTo, TimeSpan duration, ISoundOut soundOut, CancellationToken token)
        {
            var different = Math.Abs(volumeTo - volumeFrom);
            var durationInt = (int)duration.TotalMilliseconds;
            var stepCount = durationInt/WaitLength;
            var step = different / stepCount;
            var currentVolume = volumeFrom;
            for (int i = 0; i < durationInt / WaitLength; i++)
            {
                try
                {
                    await Task.Delay(WaitLength, token);
                }
                catch (TaskCanceledException)
                {
                    break;
                }

                currentVolume += volumeTo > volumeFrom ? step : -step;
                if (currentVolume < 0 || currentVolume > 1)
                {
                    //It's not exact with the float values. if we would use decimal, this code would never reach. This prevents errors
                    break;
                }

                try
                {
                    soundOut.Volume = currentVolume;
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
            }

            soundOut.Volume = volumeTo; //Because it won't be exact (because of the float)
        }
コード例 #39
0
ファイル: VolumeFading.cs プロジェクト: WELL-E/Hurricane
        protected async Task Fade(float from, float to, TimeSpan duration, bool getLouder, ISoundOut soundout)
        {
            IsFading = true;
            float different = Math.Abs(to - from);
            float step = different / ((float)duration.TotalMilliseconds / 20);
            float currentvolume = from;

            for (int i = 0; i < duration.TotalMilliseconds / 20; i++)
            {
                if (_cancel) { _cancel = false; OnCancelled(); break; }
                await Task.Delay(20);
                if (getLouder) { currentvolume += step; } else { currentvolume -= step; }
                if (currentvolume < 0 || currentvolume > 1) break;
                try
                {
                    soundout.Volume = currentvolume;
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
            }
            IsFading = false;
        }
コード例 #40
0
ファイル: MainWindow.cs プロジェクト: hoangduit/cscore
        private void button1_Click(object sender, EventArgs e)
        {
            var ofn = new OpenFileDialog();
            ofn.Filter = CodecFactory.SupportedFilesFilterEn;
            if (ofn.ShowDialog() == DialogResult.OK)
            {
                Stop();

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                    _soundOut = new WasapiOut();
                else
                    _soundOut = new DirectSoundOut();

                var source = CodecFactory.Instance.GetCodec(ofn.FileName)
                    .Loop()
                    .ChangeSampleRate(32000)
                    .ToSampleSource()
                    .AppendSource(Equalizer.Create10BandEqualizer, out _equalizer)
                    .ToWaveSource();

                _soundOut.Initialize(source);
                _soundOut.Play();
            }
        }
コード例 #41
0
ファイル: MusicPlayer.cs プロジェクト: cboseak/KoPlayer
 private void CleanupPlayback()
 {
     if (soundOut != null)
     {
         soundOut.Dispose();
         soundOut = null;
     }
     if (waveSource != null)
     {
         waveSource.Dispose();
         waveSource = null;
     }
 }
コード例 #42
0
ファイル: MusicPlayer.cs プロジェクト: cboseak/KoPlayer
        public void Open(string filename, MMDevice device)
        {
            CleanupPlayback();

            var source = CodecFactory.Instance.GetCodec(filename);

            waveSource =
                CodecFactory.Instance.GetCodec(filename)
                    .ToStereo()
                    .ChangeSampleRate(44100)
                    .ToSampleSource()
                    .AppendSource(Equalizer.Create10BandEqualizer, out equalizer)
                    .ToWaveSource(16);

            soundOut = new WasapiOut() {Latency = 100, Device = device};
            soundOut.Initialize(waveSource);
            if (this.OpenCompleted != null)
                this.OpenCompleted(this, new EventArgs());
        }
コード例 #43
0
ファイル: VolumeFading.cs プロジェクト: WELL-E/Hurricane
 public async Task FadeOut(ISoundOut soundOut, float fromVolume)
 {
     await Fade(fromVolume, 0, TimeSpan.FromMilliseconds(300), false, soundOut);
 }
コード例 #44
0
        private void CanHandleEOFTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            int sourceLength = (int)source.GetLength().TotalMilliseconds;
            Debug.WriteLine(soundOut.GetType().FullName);
            for (int i = 0; i < BasicIterationCount; i++)
            {
                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep(sourceLength + 500);
                Assert.AreEqual(source.Length, source.Position, "Source is not EOF");

                soundOut.Stop();
                source.Position = 0;

                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep(sourceLength + 500);
                Assert.AreEqual(source.Length, source.Position, "Source is not EOF");

                soundOut.Pause();
                soundOut.Resume();

                Thread.Sleep(10);

                soundOut.Stop();
                source.Position = 0;

                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep(sourceLength + 1000);
                Assert.AreEqual(source.Length, source.Position, "Source is not EOF");
                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);

                source.Position = 0;
                soundOut.Play();

                Thread.Sleep(sourceLength + 500);
                Assert.AreEqual(source.Length, source.Position, "Source is not EOF");
            }
        }
コード例 #45
0
        private void CanHandleEOFOnReplayTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            soundOut.Initialize(source);
            soundOut.Stopped += (s, e) => waitHandle.Set();

            for (int i = 0; i < BasicIterationCount; i++)
            {
                soundOut.Play();
                waitHandle.WaitOne();
                Assert.AreEqual(source.Length, source.Position, "Source is not EOF");
                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);
                source.Position = 0;
            }
        }
コード例 #46
0
 public virtual void OnTestInitialize()
 {
     _soundOut = CreateSoundOut();
     if (_soundOut == null)
         throw new Exception("No valid soundout.");
     Debug.WriteLine(_soundOut.GetType().FullName);
 }
コード例 #47
0
 public virtual void OnTestCleanup()
 {
     _soundOut.Dispose();
     _soundOut = null;
 }
コード例 #48
0
ファイル: MainWindow.cs プロジェクト: CheViana/AudioLab
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_soundOut != null)
                _soundOut.Dispose();

            _waveIn.Dispose();
            if(_writer is IDisposable)
                ((IDisposable)_writer).Dispose();

            _waveIn = null;
            _writer = null;
            _soundOut = null;

            btnStart.Enabled = deviceslist.SelectedItems.Count > 0;
            btnStop.Enabled = false;
        }
コード例 #49
0
ファイル: MainWindow.xaml.cs プロジェクト: Milfje/cscore
 public MainWindow()
 {
     InitializeComponent();
     DataContext = this;
     _soundOut = new WasapiOut();
 }
コード例 #50
0
ファイル: MainWindow.xaml.cs プロジェクト: CheViana/AudioLab
        private void OpenSource(IWaveSource source)
        {
            try
            {
                Stop(); //if playing -> stop playback
                _audioSource = source;

                _gainSource = new GainSource(source) { Gain = (float)this.Gain };

                source = SetupVisualization(_gainSource.ToWaveSource(16));

                if (WasapiOut.IsSupportedOnCurrentPlatform) // > Vista
                {
                    _soundOut = new WasapiOut(false, CSCore.CoreAudioAPI.AudioClientShareMode.Shared, 100);
                }
                else // < Vista
                {
                    _soundOut = new DirectSoundOut() { Latency = 100 };
                }

                _soundOut.Initialize(source);
                _soundOut.Stopped += OnPlaybackStopped;
                _soundOut.Play();
            }
            catch (CSCore.CoreAudioAPI.CoreAudioAPIException ex)
            {
                MessageBox.Show("Unknown CoreAudioAPI-error: 0x" + ex.ErrorCode.ToString("x"), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Stop();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unknown error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Stop();
            }
        }
コード例 #51
0
ファイル: MainWindow.xaml.cs プロジェクト: CheViana/AudioLab
 private void Stop()
 {
     if (_soundOut != null)
     {
         var soundOut = _soundOut;
         _soundOut = null;
         soundOut.Stop();
         soundOut.Dispose();
         if (soundOut.WaveSource != null)
             soundOut.WaveSource.Dispose();
     }
 }
コード例 #52
0
        private void CanReinitializeSoundOutTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < BasicIterationCount; i++)
            {
                Debug.WriteLine(soundOut.ToString());

                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep(100);

                soundOut.Stop();
                source.Position = 0;
            }
        }
コード例 #53
0
ファイル: VolumeFading.cs プロジェクト: WELL-E/Hurricane
        public async void FadeOut(double seconds, ISoundOut soundOut)
        {
            IsCrossfading = true;
            var steps = seconds / 0.2;
            var soundstep = soundOut.Volume / (float)steps;

            for (int i = 0; i < steps; i++)
            {
                if (_cancel) { _cancel = false; break; }
                await Task.Delay(200);
                try
                {
                    var value = soundOut.Volume - soundstep;
                    if (0 > value) break;
                    soundOut.Volume -= soundstep;
                }
                catch (ObjectDisposedException)
                {
                    IsCrossfading = false;
                    break;
                }
            }

            IsCrossfading = false;
            if (soundOut.PlaybackState != PlaybackState.Stopped) soundOut.Stop();
            soundOut.WaveSource.Dispose();
            soundOut.Dispose();
        }
コード例 #54
0
        private void PlaybackStoppedEventTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < BasicIterationCount; i++)
            {
                bool raised = false;
                soundOut.Stopped += (s, e) => raised = true;

                //1. wait for the event on end of stream
                soundOut.Initialize(source);
                soundOut.Play();

                Thread.Sleep((int)(source.GetLength().TotalMilliseconds + 50));
                while (soundOut.PlaybackState != PlaybackState.Stopped)
                    Thread.Sleep(10);

                soundOut.Initialize(source); //the playbackstate may be stopped but event was not fired. initialize will wait until it gets fired.

                source.Position = 0;
                Assert.IsTrue(raised);
                raised = false;

                //2. event on Stop()
                soundOut.Play();

                Thread.Sleep(50);
                soundOut.Stop();

                Assert.IsTrue(raised);
            }
        }
コード例 #55
0
ファイル: VolumeFading.cs プロジェクト: WELL-E/Hurricane
 public async Task FadeIn(ISoundOut soundOut, float toVolume)
 {
     await Fade(0, toVolume, TimeSpan.FromMilliseconds(300), true, soundOut);
 }
コード例 #56
0
        private void PlayPauseResumeBehaviourTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < BasicIterationCount; i++)
            {
                soundOut.Initialize(source);
                //--

                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                Thread.Sleep(50);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                soundOut.Resume();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);
                //--
                Thread.Sleep(250);
                //--
                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                Thread.Sleep(50);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);
                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                soundOut.Resume();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);
                //--

                soundOut.Stop();
                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                Thread.Sleep(10);

                soundOut.Stop();
                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);

                soundOut.Play();
                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Pause();
                Assert.AreEqual(PlaybackState.Paused, soundOut.PlaybackState);

                Thread.Sleep(50);

                //--
                soundOut.Stop();
                Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState);
                source.Position = 0;
            }
        }
コード例 #57
0
ファイル: VolumeFading.cs プロジェクト: WELL-E/Hurricane
 public async void CrossfadeIn(ISoundOut soundOut, float toVolume)
 {
     await Fade(0, toVolume, TimeSpan.FromSeconds(OutDuration), true, soundOut);
 }
コード例 #58
0
        private void PlayStopTestInternal(ISoundOut soundOut, IWaveSource source)
        {
            for (int i = 0; i < BasicIterationCount; i++)
            {
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();

                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();

                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
                soundOut.Initialize(source);
                soundOut.Play();
                soundOut.Stop();
            }
        }
コード例 #59
0
 private void VolumeResetTestInternal(ISoundOut soundOut, IWaveSource source)
 {
     soundOut.Initialize(source);
     soundOut.Play();
     soundOut.Volume = 0.5f;
     Assert.AreEqual(0.5f, Math.Round(soundOut.Volume, 3)); //round => directsound may causes problems because of db => lin calculations.
     Thread.Sleep(50);
     soundOut.Stop();
     soundOut.Initialize(source);
     soundOut.Play();
     Assert.AreEqual(1.0f, soundOut.Volume);
     soundOut.Stop();
 }
コード例 #60
0
ファイル: CSCoreEngine.cs プロジェクト: caesay/Hurricane
        private async void SoundOutProvider_InvalidateSoundOut(object sender, EventArgs e)
        {
            var isPlaying = IsPlaying;
            StopPlayback();
            _soundOut?.Dispose();
            _soundOut = ((CSCoreSoundOutProvider) SoundOutProvider).GetSoundOut();

            if (_soundSource != null)
            {
                _soundOut.Initialize(_soundSource);
                _soundOut.Volume = Volume;
                if (isPlaying)
                    await TogglePlayPause();
            }
        }