Beispiel #1
0
        public static void StartNewTrack()
        {
            // find out what to play
            var tracks = FindTracks().ToArray();
            var track  = tracks.Where(t => t.Mood == CurrentMood).PickRandom();

            if (track == null)
            {
                // no music? try another mood
                var others = tracks;
                if (others.Any())
                {
                    track = others.PickRandom();
                }
            }
            if (track == null)
            {
                // no music at all :(
                return;
            }

            // prepare the new track
            var           tl = track.Path.ToLower();
            WaveChannel32 wc = null;

            if (tl.EndsWith("ogg"))
            {
                wc = new WaveChannel32(new VorbisWaveReader(track.Path));
            }
            else if (tl.EndsWith("mp3"))
            {
                wc = new WaveChannel32(new Mp3FileReader(track.Path));
            }
            else if (tl.EndsWith("wav"))
            {
                wc = new WaveChannel32(new WaveFileReader(track.Path));
            }
            else
            {
                throw new Exception("Unknown audio format for file " + track.Path);
            }

            // convert to a standard format so we can mix them (e.g. a mp3 with an ogg)
            var resampler = new MediaFoundationResampler(wc, waveFormat);
            var sp        = resampler.ToSampleProvider();

            // setup our track
            wc.Volume        = musicVolume;
            wc.PadWithZeroes = false;             // to allow PlaybackStopped event to fire

            // fade between the two tracks
            mixer.RemoveMixerInput(prevTrack);
            prevTrack = curTrack;
            if (prevTrack != null)
            {
                prevTrack.BeginFadeOut(FadeDuration);
            }
            curTrack = new FadeInOutSampleProvider(sp, true);
            curTrack.BeginFadeIn(FadeDuration);
            mixer.AddMixerInput(curTrack);
            waveout.Play();
            IsPlaying = true;
        }
        private void _play()
        {
            /* Audio chain */

            // Sampling
            _wavesampler = new WaveToSampleProvider(new Wave16ToFloatProvider(_wavebuffer));

            // Fading component
            _fade = new FadeInOutSampleProvider(_wavesampler);
            _fade.BeginFadeIn(1500);

            // Notifying component
            var _notify = new NotifyingSampleProvider(_fade);

            _notify.Sample += new EventHandler <SampleEventArgs>(_notify_Sample);

            // Gain adjustment component
            _volume        = new VolumeSampleProvider(_notify);
            _volume.Volume = this.Volume;

            // Output
            Output.Init(new SampleToWaveProvider16(_volume));

            /* Playback loop */
            do
            {
                if (_cancel_play.IsCancellationRequested)
                {
                    Console.WriteLine("[Playback thread] Cancellation requested.");

                    // Fade out and stop
                    Console.WriteLine("[Playback thread] Fading out and stopping...");
                    _fade.BeginFadeOut(500);
                    Thread.Sleep(500);
                    Output.Stop();
                    Console.WriteLine("[Playback thread] Output stopped.");
                    this.Status = StreamStatus.Stopped;
                    Console.WriteLine("[Playback thread] Acknowledged as status.");

                    //_cancel_play_token.ThrowIfCancellationRequested();
                    //Console.WriteLine("[Playback thread] WARNING: Cancellation token is not cleanly set!");
                    return;
                }

                if (Output.PlaybackState != PlaybackState.Playing && _wavebuffer.BufferedDuration.TotalMilliseconds > 2750)
                {
                    // Buffer is filled enough
                    Console.WriteLine("[Playback thread] Buffer is okay now, start playback!");
                    this.Status = StreamStatus.Playing;
                    Output.Play();
                }
                else if (Output.PlaybackState == PlaybackState.Playing && _wavebuffer.BufferedDuration.TotalMilliseconds < 2250)
                {
                    // Buffer is underrunning
                    Console.WriteLine("[Playback thread] Buffer is underrunning, pausing playback...");
                    this.Status = StreamStatus.Buffering;
                    Output.Pause();
                }

                if (_bufferThread.Exception != null)
                {
                    Console.WriteLine("[Playback thread] Buffering thread is faulted, aborting playback");
                    throw new Exception("Buffering thread faulted, aborting playback");
                }

                Thread.Sleep(100);
            }while (true);
        }
        private void btnReproducir_Click(object sender, RoutedEventArgs e)
        {
            if (output != null &&
                output.PlaybackState == PlaybackState.Paused)
            {
                output.Play();
                btnReproducir.IsEnabled = false;
                btnPausa.IsEnabled      = true;
                btnDetener.IsEnabled    = true;
            }
            else
            {
                reader =
                    new AudioFileReader(txtRutaArchivo.Text);

                delay =
                    new Delay(reader);
                delay.Ganancia           = (float)sldDelayGnancia.Value;
                delay.Activo             = (bool)cbDelayActivo.IsChecked;
                delay.OffsetMilisegundos = (int)sldDelayOffset.Value;

                fades = new FadeInOutSampleProvider(
                    delay, true);
                double milisegundosFadeIn =
                    Double.Parse(txtDuracionFadeIn.Text)
                    * 1000.0;
                fades.BeginFadeIn(milisegundosFadeIn);
                fadingOut             = false;
                output                = new WaveOutEvent();
                output.DesiredLatency = 150;

                output.DeviceNumber =
                    cbSalida.SelectedIndex;

                output.PlaybackStopped += Output_PlaybackStopped;

                volume =
                    new EfectoVolumen(fades);

                volume.Volume =
                    (float)sldVolumen.Value;

                output.Init(volume);
                output.Play();

                btnDetener.IsEnabled    = true;
                btnPausa.IsEnabled      = true;
                btnReproducir.IsEnabled = false;

                lblTiempoTotal.Text =
                    reader.TotalTime.ToString().Substring(0, 8);
                lblTiempoActual.Text =
                    reader.CurrentTime.ToString().Substring(0, 8);
                sldReproduccion.Maximum =
                    reader.TotalTime.TotalSeconds;
                sldReproduccion.Value =
                    reader.CurrentTime.TotalSeconds;

                timer.Start();
            }
        }
 public LoopVolumeWaveProvider16(LoopWaveStream LoopWaveStream) : base(LoopWaveStream)
 {
     SourceLoopWaveStream = LoopWaveStream;
     FadeInOutProvider    = new FadeInOutSampleProvider(SourceLoopWaveStream.ToSampleProvider());
 }
        private void btnReproducir_Click(object sender, RoutedEventArgs e)
        {
            //evitar duplicado despues del primer play
            //si ademas de ya tener el output esta pausado
            if (output != null && output.PlaybackState == PlaybackState.Paused)
            {
                output.Play();

                //activamos y desactivamos los botones para poner restricciones en la interfaz
                btnReproducir.IsEnabled = false;
                btnPausa.IsEnabled      = true;
                btnDetener.IsEnabled    = true;
            }
            else
            {
                reader = new AudioFileReader(txtRutaArchivo.Text);

                delay                    = new Delay(reader);
                delay.Ganancia           = (float)sldDelayGanancia.Value;
                delay.Activo             = (bool)cbDelayActivo.IsChecked;
                delay.OffsetMilisegundos = (int)sldDelayOffset.Value;

                //Se le da el archivo y si queremos que inicie en total silencio o no
                fades = new FadeInOutSampleProvider(delay, true);
                //se transforman los segundos a mini segundos para la duracion del fade
                double milisegundosFadeIn = Double.Parse(txtDuracionFadeIn.Text) * 1000.0;
                fades.BeginFadeIn(milisegundosFadeIn);

                //hay que reiniciar cuando se reinicie la cancion
                fadingOut = false;
                output    = new WaveOutEvent();
                //aqui se establece la latencia al buffer para que se corte menos el audio pero la primera vez de llenado del buffer tardara mas
                output.DesiredLatency = 150;

                //aqui se cambia donde se reproduce
                output.DeviceNumber = cbSalida.SelectedIndex;

                //se añaden reacciones a los eventos con += pues asi se sobrecarga el operador
                //con tab crea la funcion visual (output_playbackstopped)
                output.PlaybackStopped += Output_PlaybackStopped;

                volume        = new VolumeSampleProvider(fades);
                volume.Volume = (float)sldVolumen.Value;

                //inisializamos el output
                output.Init(volume);
                output.Play();

                //activamos y desactivamos los botones para poner restricciones en la interfaz
                btnDetener.IsEnabled    = true;
                btnPausa.IsEnabled      = true;
                btnReproducir.IsEnabled = false;

                //se quitan los milisegundos y eso
                lblTiempoFinal.Text = reader.TotalTime.ToString().Substring(0, 8);

                //se le asigna a la barrita el tiempo total que dura la cancion como double
                sldReproduccion.Maximum = reader.TotalTime.TotalSeconds;
                //se le asigna el valor actual a la barrita
                sldReproduccion.Value = reader.CurrentTime.TotalSeconds;
                //asi se inicia el contador
                timer.Start();
            }
        }
        private int FadeInOut(Track track1, Track track2, int averageFadeDuration, TrackCollection collection)
        {
            int startFadeIn1  = CalculateStartFadeIn(track1);
            var fileReader    = new Mp3FileReader(track1.Path);
            var startTimeSpan = new TimeSpan(0, 0, 0, 0, startFadeIn1);
            var fade          = new FadeInOutSampleProvider(fileReader.ToSampleProvider().Skip(startTimeSpan), false);

            int fadeInDuration1, fadeOutDuration1, fadeInDuration2;

            if (track1 == collection[0])
            {
                fadeInDuration1 = CalculateFadeInDuration(track1);
            }
            else
            {
                fadeInDuration1 = averageFadeDuration;
            }
            if (track1 == collection[collection.Count - 1])
            {
                fadeOutDuration1    = CalculateFadeOutDuration(track1);
                averageFadeDuration = 0;
            }
            else
            {
                fadeOutDuration1 = CalculateFadeOutDuration(track1);
                fadeInDuration2  = CalculateFadeInDuration(track2);
                var averageFadesDuration = (fadeOutDuration1 + fadeInDuration2) / 2;
                averageFadeDuration = averageFadesDuration;
                fadeOutDuration1    = averageFadeDuration;
            }
            var trackDuration = (track1.Duration - startFadeIn1) + fadeInDuration1 + averageFadeDuration;

            if (track2 == null)
            {
                trackDuration += averageFadeDuration;
            }

            long bufferSize;

            if (_currentMixDuration < MixDuration)
            {
                bufferSize = (fileReader.Length) / 2 - ((fadeOutDuration1 + fadeInDuration1 + startFadeIn1 - 2000) / 1000) * SamplesPerSecond;
            }
            else
            {
                bufferSize = (MixDuration - _currentMixDuration) * SamplesPerSecond;
            }

            var overlaySize = (fadeOutDuration1 / 1000) * SamplesPerSecond;

            if (bufferSize < overlaySize)
            {
                bufferSize = overlaySize;
            }

            var buffer = new float[bufferSize];

            fade.BeginFadeIn(fadeInDuration1);
            fade.Read(buffer, 0, (int)(bufferSize - overlaySize));
            fade.BeginFadeOut(fadeOutDuration1);
            fade.Read(buffer, (int)(bufferSize - overlaySize), overlaySize);

            if (_savedOverlay != null)
            {
                buffer = ApplyOverlay(buffer, _savedOverlay);
            }

            _waveFileWriter.WriteSamples(buffer, 0, (int)(bufferSize - overlaySize));
            _waveFileWriter.Flush();

            _savedOverlay = new float[overlaySize];
            for (var i = 0; i < overlaySize; i++)
            {
                _savedOverlay[i] = buffer[(bufferSize - overlaySize) + i];
            }

            _currentMixDuration += trackDuration;

            return(averageFadeDuration);
        }
Beispiel #7
0
        // Boton Reproducir
        private void btn_Reproducir_Click(object sender, RoutedEventArgs e)
        {
            if (output != null && output.PlaybackState == PlaybackState.Paused)
            {
                sld_Reproduccion.IsEnabled = true;
                output.Play();
                btn_Reproducir.IsEnabled     = false;
                btn_Elegir_Archivo.IsEnabled = false;
                btn_Pausa.IsEnabled          = true;
                btn_Detener.IsEnabled        = true;
            }
            else
            {
                if (txt_Direccion_Archivo.Text != "")
                {
                    reader = new AudioFileReader(txt_Direccion_Archivo.Text);

                    delay = new Delay(reader);

                    delay.Ganancia = (float)sld_Gain_Cantidad.Value;

                    delay.OffsetMilisegundos = (int)sld_Delay_Offset.Value;

                    if (sld_Delay_Offset.IsEnabled == true)
                    {
                        delay.Activo = true;
                    }
                    else
                    {
                        delay.Activo = false;
                    }

                    fades = new FadeInOutSampleProvider(delay, true);
                    double milisegundosFadeIn = Double.Parse(txt_FadeIn.Text) * 1000.0;
                    fades.BeginFadeIn(milisegundosFadeIn);
                    fadingOut = false;

                    output = new WaveOutEvent();

                    // Mientras más alta sea la latencia, más info se podrá almacenar en el búffer, a costa de que éste tardará un poco más (la 1ra vez) en llenarse
                    output.DesiredLatency = 150; // 150 ms

                    output.DeviceNumber = cb_Salida.SelectedIndex;

                    // Los rayitos(eventos) responden a funciones mediante el operador +=
                    output.PlaybackStopped += Output_PlaybackStopped;

                    volume = new EfectoVolumen(fades);

                    volume.Volume = (float)sld_Volumen.Value;

                    output.Init(volume);
                    output.Play();

                    sld_Reproduccion.IsEnabled   = true;
                    btn_Pausa.IsEnabled          = true;
                    btn_Detener.IsEnabled        = true;
                    btn_Reproducir.IsEnabled     = false;
                    btn_Elegir_Archivo.IsEnabled = false;
                    cb_Salida.IsHitTestVisible   = false;
                    cb_Salida.IsEditable         = false;
                    cb_Salida.Focusable          = false;

                    lbl_Tiempo_Total.Text  = reader.TotalTime.ToString().Substring(0, 8);
                    lbl_Tiempo_Actual.Text = reader.CurrentTime.ToString().Substring(0, 8);

                    sld_Reproduccion.Maximum = reader.TotalTime.TotalSeconds;
                    sld_Reproduccion.Minimum = 0;

                    timer.Start();
                }
            }
        }