Exemplo n.º 1
0
 private void OnButtonPlayClick(object sender, EventArgs args)
 {
     try
     {
         if (!CheckAudioLoaded())
         {
             return;
         }
         if (outputDevice == null)
         {
             if (!string.IsNullOrEmpty(tb_Mp3FilePath.Text))
             {
                 audioFile = new AudioFileReader(tb_Mp3FilePath.Text);
                 if (outputDevice == null)
                 {
                     outputDevice = new WaveOutEvent();
                     outputDevice.PlaybackStopped += OnPlaybackStopped;
                 }
                 outputDevice.Init(audioFile);
             }
         }
         outputDevice?.Play();
     }
     catch (Exception ex)
     {
     }
 }
 public void Resume()
 {
     if (this.PlayState != PlayState.Paused)
     {
         throw new ArgumentException("只能从暂停状态恢复播放");
     }
     outputDevice?.Play();
 }
        /// <summary>
        /// Starts the media capturing/source devices.
        /// </summary>
        public Task StartAudio()
        {
            if (!_isStarted)
            {
                _isStarted = true;
                _waveOutEvent?.Play();
                _waveInEvent?.StartRecording();
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 4
0
        }// Pauses the music without completely disposing it

        /// <summary>
        /// Resumes playback.
        /// </summary>
        public static void ResumeMusic()
        {
            if (paused)
            {
                outputDevice?.Play();
            }
            //playing = true;
            paused = false;
            if (Properties.Settings.Default.General_DiscordIntegration)
            {
                ATL.Track metadata = new ATL.Track(filePath);
                UpdateRPC("play", metadata.Artist, metadata.Title);
            }
        }// Resumes music that has been paused
Exemplo n.º 5
0
        public void TogglePaused()
        {
            switch (playbackState)
            {
            case PlaybackState.Paused:
                playbackState = PlaybackState.Playing;
                waveOut1?.Play();
                waveOut2?.Play();
                break;

            case PlaybackState.Playing:
                playbackState = PlaybackState.Paused;
                waveOut1?.Pause();
                waveOut2?.Pause();
                break;

            default:
                break;
            }
        }
Exemplo n.º 6
0
        void DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                for (int i = 0; i < LoopCount; i++)
                {
                    MixedWave.Position = 0;
                    StopWatch.Reset();
                    WaveOut?.Play();
                    StopWatch.Start();

                    for (int j = 0; j < WaveMonitorLoopCount; j++)
                    {
                        if (WaveInitializationInProgress)   // wave was changed mid play
                        {
                            break;
                        }

                        Thread.Sleep(WaveMonitorLoopLength_ms);

                        // Thread.Sleep() is very inaccurate. Let's check the elapsed time to avoid excess drifting.
                        if (StopWatch.ElapsedMilliseconds > PlayDurationMs)
                        {
                            break;
                        }
                    }

                    StopWatch.Stop();
                    if (WaveInitializationInProgress)
                    {
                        return;
                    }

                    WaveOut?.Stop();
                }
            }
            catch (Exception)
            {
                // intentionally ignore
            }
        }
Exemplo n.º 7
0
        public TalkingTask(IPAddress ip)
        {
            IP        = ip;
            task_send = new Thread(() =>
            {
                bool recording = false;
                bool stop      = false;


                WaveInEvent wi        = new WaveInEvent();
                wi.DeviceNumber       = 0;
                wi.WaveFormat         = new WaveFormat(Toolbox.RATE, 2);
                wi.BufferMilliseconds = (int)((double)(Toolbox.BUFFERSIZE / 2) / (double)Toolbox.RATE * 1000.0);
                wi.DataAvailable     += new EventHandler <WaveInEventArgs>(AudioDataAvailable);

                while (true)
                {
                    Parallel.Invoke(new Action(() => { stop = _stop; }));
                    if (stop)
                    {
                        if (recording)
                        {
                            wi.StopRecording();
                            recording         = false;
                            wi.DataAvailable -= AudioDataAvailable;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (!recording)
                        {
                            try
                            {
                                wi.StartRecording();
                                recording = true;
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            });
            task_send.IsBackground = true;


            task_play = new Thread(() =>
            {
                UdpClient client          = new UdpClient(45002);
                IPEndPoint remoteEndPoint = new IPEndPoint(IP, 0);
                bool stop = false;

                while (true)
                {
                    Parallel.Invoke(new Action(() => { stop = _stop; }));
                    if (stop)
                    {
                        break;
                    }
                    Byte[] rec    = client.Receive(ref remoteEndPoint);
                    string recstr = Encoding.ASCII.GetString(rec);
                    string header = recstr.Substring(0, Definitions.DISCONNECTING.Length);
                    if (header.Equals(Definitions.DISCONNECTING))
                    {
                        DisconnectionRequestEvent?.Invoke();
                        _stop = true;
                        break;
                    }
                    else
                    {
                        WaveOutEvent wo = new WaveOutEvent();
                        wo.Init(new RawSourceWaveStream(rec, 0, rec.Length, new WaveFormat(Toolbox.RATE, 2)));
                        wo.Play();
                    }
                }
            });
            task_play.IsBackground = true;
        }
Exemplo n.º 8
0
        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();
            }
        }
Exemplo n.º 9
0
        void OnDataAvailable(object sender, WaveInEventArgs e)
        {
            byte[] buffer        = e.Buffer;
            int    bytesGrabados = e.BytesRecorded;


            double acumulador              = 0;
            double numMuestras             = bytesGrabados / 2;
            int    exponente               = 1;
            int    numeroMuestrasComplejas = 0;
            int    bitsMaximos             = 0;

            do //1,200
            {
                bitsMaximos = (int)Math.Pow(2, exponente);
                exponente++;
            } while (bitsMaximos < numMuestras);

            //bitsMaximos = 2048
            //exponente = 12

            //numeroMuestrasComplejas = 1024
            //exponente = 10

            exponente -= 2;
            numeroMuestrasComplejas = bitsMaximos / 2;

            Complex[] muestrasComplejas =
                new Complex[numeroMuestrasComplejas];

            for (int i = 0; i < bytesGrabados; i += 2)
            {
                // byte i =  0 1 1 0 0 1 1 1
                //byte i+1 = 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 1
                // or      = 0 1 1 0 0 1 1 1 0 1 1 0 0 1 1 1
                short muestra =
                    (short)Math.Abs((buffer[i + 1] << 8) | buffer[i]);
                //lblMuestra.Text = muestra.ToString();
                //sldVolumen.Value = (double)muestra;

                float muestra32bits = (float)muestra / 32768.0f;
                sldVolumen.Value = Math.Abs(muestra32bits);

                if (i / 2 < numeroMuestrasComplejas)
                {
                    muestrasComplejas[i / 2].X = muestra32bits;
                }
                //acumulador += muestra;
                //numMuestras++;
            }
            //double promedio = acumulador / numMuestras;
            //sldVolumen.Value = promedio;
            //writer.Write(buffer, 0, bytesGrabados);

            FastFourierTransform.FFT(true, exponente, muestrasComplejas);
            float[] valoresAbsolutos =
                new float[muestrasComplejas.Length];
            for (int i = 0; i < muestrasComplejas.Length; i++)
            {
                valoresAbsolutos[i] = (float)
                                      Math.Sqrt((muestrasComplejas[i].X * muestrasComplejas[i].X) +
                                                (muestrasComplejas[i].Y * muestrasComplejas[i].Y));
            }

            int indiceMaximo =
                valoresAbsolutos.ToList().IndexOf(
                    valoresAbsolutos.Max());

            float frecuenciaFundamental =
                (float)(indiceMaximo * waveIn.WaveFormat.SampleRate) / (float)valoresAbsolutos.Length;

            char letra = 'A';

            lblFrecuencia.Text = frecuenciaFundamental.ToString();
            lblDisplay.Text    = letra.ToString();
            if (frecuenciaFundamental >= 80 && frecuenciaFundamental <= 120)
            {
                if (waveOut != null && reader != null)
                {
                    if (waveOut.PlaybackState == PlaybackState.Playing)
                    {
                        waveOut.Stop();
                    }
                    delayProvider = new Delay(reader);
                    waveOut.Init(delayProvider);
                    waveOut.Play();
                }
                letra = 'A';
            }
            else if (frecuenciaFundamental >= 180 && frecuenciaFundamental <= 220)
            {
                letra = 'B';
            }
            else if (frecuenciaFundamental >= 280 && frecuenciaFundamental <= 320)
            {
                letra = 'C';
            }
            else if (frecuenciaFundamental >= 380 && frecuenciaFundamental <= 420)
            {
                letra = 'D';
            }
            else if (frecuenciaFundamental >= 480 && frecuenciaFundamental <= 520)
            {
                letra = 'E';
            }
            else if (frecuenciaFundamental >= 580 && frecuenciaFundamental <= 620)
            {
                letra = 'F';
            }
            else if (frecuenciaFundamental >= 680 && frecuenciaFundamental <= 720)
            {
                letra = 'G';
            }
            else if (frecuenciaFundamental >= 780 && frecuenciaFundamental <= 820)
            {
                letra = 'H';
            }
            else if (frecuenciaFundamental >= 880 && frecuenciaFundamental <= 920)
            {
                letra = 'I';
            }
            else if (frecuenciaFundamental >= 980 && frecuenciaFundamental <= 1020)
            {
                letra = 'J';
            }
            else if (frecuenciaFundamental >= 1080 && frecuenciaFundamental <= 1120)
            {
                letra = 'K';
            }
            else if (frecuenciaFundamental >= 1180 && frecuenciaFundamental <= 1220)
            {
                letra = 'L';
            }
            else if (frecuenciaFundamental >= 1280 && frecuenciaFundamental <= 1320)
            {
                letra = 'M';
            }
            else if (frecuenciaFundamental >= 1380 && frecuenciaFundamental <= 1420)
            {
                letra = 'N';
            }
            else if (frecuenciaFundamental >= 1480 && frecuenciaFundamental <= 1520)
            {
                letra = 'O';
            }
            else if (frecuenciaFundamental >= 1580 && frecuenciaFundamental <= 1620)
            {
                letra = 'P';
            }
            else if (frecuenciaFundamental >= 1680 && frecuenciaFundamental <= 1720)
            {
                letra = 'Q';
            }
            else if (frecuenciaFundamental >= 1780 && frecuenciaFundamental <= 1820)
            {
                letra = 'R';
            }
            else if (frecuenciaFundamental >= 1880 && frecuenciaFundamental <= 1920)
            {
                letra = 'S';
            }
            else if (frecuenciaFundamental >= 1980 && frecuenciaFundamental <= 2020)
            {
                letra = 'T';
            }
            else if (frecuenciaFundamental >= 2080 && frecuenciaFundamental <= 2120)
            {
                letra = 'U';
            }
            else if (frecuenciaFundamental >= 2180 && frecuenciaFundamental <= 2220)
            {
                letra = 'V';
            }
            else if (frecuenciaFundamental >= 2280 && frecuenciaFundamental <= 2320)
            {
                letra = 'W';
            }
            else if (frecuenciaFundamental >= 2380 && frecuenciaFundamental <= 2420)
            {
                letra = 'X';
            }
            else if (frecuenciaFundamental >= 2480 && frecuenciaFundamental <= 2520)
            {
                letra = 'Y';
            }
            else if (frecuenciaFundamental >= 2580 && frecuenciaFundamental <= 2620)
            {
                letra = 'Z';
            }
            else if (frecuenciaFundamental >= 2680 && frecuenciaFundamental <= 2720)
            {
            }
        }
Exemplo n.º 10
0
 private void btnPlay_Click(object sender, RoutedEventArgs e)
 {
     outputDevice?.Play();
     btnPlay.IsEnabled  = false;
     btnPause.IsEnabled = true;
 }
Exemplo n.º 11
0
 private void OnButtonPlayClick(object sender, EventArgs e)
 {
     outputDevice?.Play();
 }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Animação ASCII : Bad Apple");

            List <String> frames      = new List <String>();
            int           quantFrames = Directory.GetFiles(@"BadApple\frames").Length;
            int           frameIndex  = 1;

            int width  = Console.WindowWidth - 1;
            int height = Console.WindowHeight - 1;

            Console.Write("Loading the animation frames, please wait : ");
            while (true)
            {
                string frame = @"BadApple\frames\" + frameIndex.ToString() + ".png";

                if (!File.Exists(frame))
                {
                    break;
                }

                using (Bitmap image = new Bitmap(frame))
                {
                    Bitmap   bmp = new Bitmap(width, height);
                    Graphics g   = Graphics.FromImage(bmp);
                    g.DrawImage(image, 0, 0, width, height);

                    StringBuilder sb    = new StringBuilder();
                    String        chars = " .*#%@";

                    for (int y = 0; y < bmp.Height; y++)
                    {
                        for (int x = 0; x < bmp.Width; x++)
                        {
                            int index = (int)(bmp.GetPixel(x, y).GetBrightness() * chars.Length);

                            if (index < 0)
                            {
                                index = 0;
                            }
                            else if (index >= chars.Length)
                            {
                                index = chars.Length - 1;
                            }
                            sb.Append(chars[index]);
                        }
                        sb.Append("\n");
                    }

                    frames.Add(sb.ToString());
                    frameIndex++;

                    int percentage = (int)((frames.Count / (float)(quantFrames)) * 100);

                    Console.SetCursorPosition(43, Console.CursorTop);
                    Console.Write("|" + percentage.ToString() + "%" + " | processed frames : " + frames.Count.ToString() + " ");
                }
            }

            AudioFileReader reader = new AudioFileReader(@"BadApple\audio.wav");
            WaveOutEvent    woe    = new WaveOutEvent();

            woe.Init(reader);
            Console.WriteLine("\n\n press ENTER to start!");
            Console.ReadLine();
            woe.Play();

            while (true)
            {
                float percentage = woe.GetPosition() / (float)reader.Length;
                int   frame      = (int)(frames.Count * percentage);
                if (frame >= frames.Count)
                {
                    break;
                }
                Console.SetCursorPosition(0, 0);
                Console.WriteLine(frames[frame].ToString());
            }
            Console.WriteLine("The END, bye:)");
            Console.ReadLine();
        }
Exemplo n.º 13
0
 /// <summary>
 /// Starts playing the track.
 /// </summary>
 public void Play()
 {
     player.Play();
 }
Exemplo n.º 14
0
        private void PopDownAttachBoy()
        {
            if (sm_kp != _sm_kp.TTSMODE)
            {
                return;
            }
            attachboy.Hide();
            sm_kp = _sm_kp.NORMAL;
            attachboy.hwndobject.SendMessage(WindowScrape.Constants.WM.ACTIVATE, 0, 0);
            attachboy.hwndobject.SendMessage(WindowScrape.Constants.WM.SETFOCUS, 0, 0);
            //now speak the text!)
            string text = (string)(attachboy.StebinTextBox.Text);

//            hwndobject.

            if (text == "")
            {
                return;
            }
            if (MoonbaseCheckbox.IsChecked == true)
            {
                text = memetext(text);
            }

            PressAppropriatePTTButton(true);

            new Thread(new ThreadStart(() =>
            {
                //save as a sound file
                const string abusedFile = "abusedFile_overlay.wav";
                using (var tts = new FonixTalkEngine())
                {
                    tts.Voice = (TtsVoice)Enum.Parse(typeof(TtsVoice), CURRENT_VOICESELECTOR_VALUE);


                    tts.SpeakToWavFile(abusedFile, text);
                }

                if (OVERLAYPLAYBACKCHECKBOXCHECKED)
                {
                    //System.IO.File.Copy(abusedFile, "copyboy", true);
                    //playback on speaker
                    string SelectedName = abusedFile;
                    Thread thread       = new Thread(new ParameterizedThreadStart((__SelectedName) =>
                    {
                        string _SelectedName = (string)__SelectedName;
                        //https://github.com/naudio/NAudio
                        try
                        {
                            using (var audioFile = new AudioFileReader(_SelectedName))
                            {
                                int selDevice = -1;

                                {
                                    for (int n = -1; n < WaveOut.DeviceCount; n++)
                                    {
                                        var caps = WaveOut.GetCapabilities(n);
                                        if (caps.ProductName.StartsWith(CURRENT_SPEAKER_VALUE))
                                        {
                                            selDevice = n;
                                            break;
                                        }
                                    }
                                }
                                using (var outputDevice = new WaveOutEvent()
                                {
                                    DeviceNumber = selDevice
                                })
                                {
                                    outputDevice.Init(audioFile);
                                    outputDevice.Volume = (float)percentagevolume;
                                    outputDevice.Play();
                                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                                    {
                                        Thread.Sleep(1000);
                                    }
                                }
                            }
                        }
                        catch (System.Runtime.InteropServices.COMException e3)
                        { Console.WriteLine(e3); }
                    }));
                    thread.Start(SelectedName);
                }


                //////////
                //now output from the sound file
                using (var audioFile = new AudioFileReader(abusedFile))
                {
                    int selDevice = -1;

                    {
                        for (int n = -1; n < WaveOut.DeviceCount; n++)
                        {
                            var caps = WaveOut.GetCapabilities(n);
                            if (caps.ProductName.StartsWith(CURRENT_MIC_VALUE))
                            {
                                selDevice = n;
                                break;
                            }
                        }
                    }
                    using (var outputDevice = new WaveOutEvent()
                    {
                        DeviceNumber = selDevice
                    })
                    {
                        outputDevice.Init(audioFile);
                        outputDevice.Volume = (float)percentagevolume;
                        outputDevice.Play();
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(1000);
                        }
                        PressAppropriatePTTButton(false);
                    }
                }
            })).Start();
        }
Exemplo n.º 15
0
        private void PrepNextAudioType()
        {
            if (liveVoice)
            {
                return;
            }

            switch (nextOutputMode)
            {
            case OutputMode.audio:
            {
                Debug.WriteLine($"Changing Audio to {currentSong.DisplayName}");

                //MainForm.StatusText = $"Playing {currentSong.DisplayName}";
                audioOutSampler           = new SampleChannel(audioFileReader);
                audioOut.PlaybackStopped -= audioOut_PlaybackStopped;
                audioOut = new WaveOutEvent();
                audioOut.Init(audioOutSampler);
                audioOut.PlaybackStopped -= audioOut_PlaybackStopped;
                audioOut.PlaybackStopped += audioOut_PlaybackStopped;
                audioOut.Play();
                busy = false;

                FadeInSound();

                break;
            }

            case OutputMode.noise:
            {
                //MainForm.StatusText = $"Generating {noiseColor} Noise";
                noiseGeneratorGains = 0.0001f;
                nextGenerator.Gain  = noiseGeneratorGains;
                pinkGenerator.Gain  = noiseGeneratorGains;
                whiteGenerator.Gain = noiseGeneratorGains;
                noiseOut            = new WaveOutEvent();
                noiseOut.Init(nextGenerator);
                noiseOut.Play();
                busy = false;

                FadeInSound();

                break;
            }
            //case OutputMode.voiceReplay:
            //    {
            //        //MainForm.StatusText = $"Playing {currentPlayback.DisplayName}";
            //        voiceReplaySampler = new SampleChannel(audioFileReader);
            //        voiceReplayOut = new WaveOutEvent();
            //        voiceReplayOut.Init(voiceReplaySampler);
            //        voiceReplayOut.Play();

            //        FadeInSound();

            //        break;
            //    }
            default:
            {
                currentOutputMode = nextOutputMode;

                busy = false;

                FadeInSound();
                break;
            }
            }
        }
Exemplo n.º 16
0
        public void Button_Click(object o, RoutedEventArgs e)
        {
            Button b = (Button)o;

            switch (b.Name)
            {
            case "GoButton":
                string text = TextBoxHandle.Text;


                TextBoxHandle.Text = "";
                Console.WriteLine(text);
                if ((automeme.IsChecked == true))
                {
                    text = memetext(text);
                }
                //save as a sound file
                const string fileName = "abusedFile.wav";

                /*using (var reader = new SpeechSynthesizer())
                 * {
                 *  foreach (var x in reader.GetInstalledVoices())
                 *      Console.WriteLine(x.VoiceInfo.Name);
                 *  reader.Rate = (int)-2;
                 *  reader.SetOutputToWaveFile(fileName);
                 *  //https://stackoverflow.com/questions/16021302/c-sharp-save-text-to-speech-to-mp3-file
                 *  reader.Speak(text);
                 * }*/

                using (var tts = new FonixTalkEngine())
                {
                    tts.Voice = (TtsVoice)Enum.Parse(typeof(TtsVoice), VoiceSelector.Text);


                    tts.SpeakToWavFile(fileName, text);
                }



                //////////
                //now output from the sound file
                using (var audioFile = new AudioFileReader(fileName))
                {
                    int selDevice = -1;
                    for (int n = -1; n < WaveOut.DeviceCount; n++)
                    {
                        var caps = WaveOut.GetCapabilities(n);
                        if (caps.ProductName.Contains("CABLE Input"))
                        {
                            selDevice = n;
                            break;
                        }
                    }
                    using (var outputDevice = new WaveOutEvent()
                    {
                        DeviceNumber = selDevice
                    })
                    {
                        outputDevice.Init(audioFile);
                        outputDevice.Volume = (float)percentagevolume;
                        outputDevice.Play();
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(1000);
                        }
                    }
                }



                break;

            case "CloseButton":
                Environment.Exit(0);
                break;
            }
        }
Exemplo n.º 17
0
        private void DataAvailable(object sender, WaveInEventArgs e)
        {
            if (targetRampedUp && rampingup && curdelay < targetMs && !quickramp)
            {
                var stretchedbuffer = Stretch(e.Buffer, (1.00 + (realRampSpeed / (100.0 * realRampFactor))), silenceThreshold);
                buffer.AddSamples(stretchedbuffer, 0, stretchedbuffer.Length);
                curdelay = (int)buffer.BufferedDuration.TotalMilliseconds;
                if (smoothRampEnabled)
                {
                    if ((targetMs - curdelay) > endRampTime && !almostDoneRampingUp)
                    {
                        if (realRampSpeed < (rampSpeed * realRampFactor))
                        {
                            realRampSpeed++;
                        }
                        else if (realRampSpeed > (rampSpeed * realRampFactor))
                        {
                            realRampSpeed--;
                        }

                        double tempEndRampTime = 0;
                        for (int i = 0; i < realRampSpeed; i++)
                        {
                            tempEndRampTime += 1.000 * i / realRampFactor;
                        }
                        endRampTime = (int)tempEndRampTime;
                    }
                    else
                    {
                        if (realRampSpeed > realRampFactor)
                        {
                            realRampSpeed--;
                        }
                        else
                        {
                            realRampSpeed = realRampFactor;
                        }
                        almostDoneRampingUp = true;
                    }
                }
                else
                {
                    realRampSpeed = rampSpeed;
                }

                //ramping = false;
                if (curdelay >= targetMs)
                {
                    rampingup = false;
                    quickramp = false;
                    if (output.PlaybackState == PlaybackState.Paused)
                    {
                        output.Play();
                    }
                }
            }

            else if ((curdelay > targetMs || !targetRampedUp) && rampingdown && curdelay > output.DesiredLatency)
            {
                //Ramp down to the target
                var stretchedbuffer = Stretch(e.Buffer, (1.00 + (realRampSpeed / (100.0 * realRampFactor))), silenceThreshold);
                buffer.AddSamples(stretchedbuffer, 0, stretchedbuffer.Length);
                curdelay = (int)buffer.BufferedDuration.TotalMilliseconds;

                int realTarget = 0;
                if (targetRampedUp)
                {
                    realTarget = targetMs;
                }

                if (smoothRampEnabled)
                {
                    if ((realTarget - curdelay) < endRampTime && !almostDoneRampingDown)
                    {
                        if (realRampSpeed > (-1 * rampSpeed * realRampFactor) && realRampSpeed / realRampFactor > -99)
                        {
                            realRampSpeed--;
                        }
                        else if (realRampSpeed < (-1 * rampSpeed * realRampFactor))
                        {
                            realRampSpeed++;
                        }


                        double tempEndRampTime = 0 - output.DesiredLatency;
                        if (targetRampedUp)
                        {
                            tempEndRampTime = 0;
                        }

                        for (int i = 0; i > realRampSpeed; i--)
                        {
                            tempEndRampTime += 1.000 * i / realRampFactor;
                        }
                        endRampTime = (int)tempEndRampTime;
                    }
                    else
                    {
                        if (realRampSpeed < (-1 * realRampFactor))
                        {
                            realRampSpeed++;
                        }
                        else
                        {
                            realRampSpeed = -1 * realRampFactor;
                        }
                        almostDoneRampingDown = true;
                    }
                }
                else
                {
                    if (rampSpeed < 100)
                    {
                        realRampSpeed = -1 * rampSpeed;
                    }
                    else
                    {
                        realRampSpeed = -99;
                    }
                }

                if ((curdelay <= targetMs && targetRampedUp) || curdelay <= output.DesiredLatency)
                {
                    rampingdown = false;
                }
            }
            else
            {
                if (realRampSpeed == 0)
                {
                    buffer.AddSamples(Stretch(e.Buffer, 1.00), 0, e.BytesRecorded);
                    curdelay = (int)buffer.BufferedDuration.TotalMilliseconds;
                }
                else
                {
                    if (smoothRampEnabled)
                    {
                        if (curdelay > 200)
                        {
                            var stretchedbuffer = Stretch(e.Buffer, (1.00 + (realRampSpeed / (100.0 * realRampFactor))), silenceThreshold);
                            buffer.AddSamples(stretchedbuffer, 0, stretchedbuffer.Length);
                            if (realRampSpeed > 0)
                            {
                                realRampSpeed--;
                            }
                            else if (realRampSpeed < 0)
                            {
                                realRampSpeed++;
                            }
                        }
                        else
                        {
                            realRampSpeed = 0;
                        }
                    }
                    else
                    {
                        realRampSpeed = 0;
                    }
                }

                curdelay              = (int)buffer.BufferedDuration.TotalMilliseconds;
                endRampTime           = 0;
                almostDoneRampingDown = false;
                almostDoneRampingUp   = false;
                if (curdelay >= targetMs)
                {
                    rampingup = false;
                    quickramp = false;
                    if (output.PlaybackState == PlaybackState.Paused)
                    {
                        output.Play();
                    }
                }
            }
            if (targetRampedUp && curdelay >= targetMs)
            {
                rampingup = false;
            }
            else if ((curdelay <= targetMs && targetRampedUp) || curdelay <= output.DesiredLatency)
            {
                rampingdown = false;
            }
            if (buffer.BufferedDuration.TotalMilliseconds > output.DesiredLatency && !quickramp && output.PlaybackState != PlaybackState.Playing)
            {
                output.Play();
            }
        }
Exemplo n.º 18
0
 private void TheMouseDown(object sender, MouseEventArgs e)
 {
     player.Play();
     IsDown = true;
     MousePressedPosition = e.Location;
 }
Exemplo n.º 19
0
        // This sample shows you how you can use SetAudioFormatCallback and SetAudioCallbacks. It does two things:
        // 1) Play the sound from the specified video using NAudio
        // 2) Extract the sound into a file using NAudio

        static void Main(string[] args)
        {
            Core.Initialize();

            using var libVLC = new LibVLC("--verbose=2");
            using var media  = new Media(libVLC,
                                         new Uri("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"),
                                         ":no-video");
            using var mediaPlayer = new MediaPlayer(media);

            using var outputDevice = new WaveOutEvent();
            var waveFormat   = new WaveFormat(8000, 16, 1);
            var writer       = new WaveFileWriter("sound.wav", waveFormat);
            var waveProvider = new BufferedWaveProvider(waveFormat);

            outputDevice.Init(waveProvider);

            mediaPlayer.SetAudioFormatCallback(AudioSetup, AudioCleanup);
            mediaPlayer.SetAudioCallbacks(PlayAudio, PauseAudio, ResumeAudio, FlushAudio, DrainAudio);

            mediaPlayer.Play();
            mediaPlayer.Time = 20_000; // Seek the video 20 seconds
            outputDevice.Play();

            Console.WriteLine("Press 'q' to quit. Press any other key to pause/play.");
            while (true)
            {
                if (Console.ReadKey().KeyChar == 'q')
                {
                    break;
                }

                if (mediaPlayer.IsPlaying)
                {
                    mediaPlayer.Pause();
                }
                else
                {
                    mediaPlayer.Play();
                }
            }

            void PlayAudio(IntPtr data, IntPtr samples, uint count, long pts)
            {
                int bytes  = (int)count * 2; // (16 bit, 1 channel)
                var buffer = new byte[bytes];

                Marshal.Copy(samples, buffer, 0, bytes);

                waveProvider.AddSamples(buffer, 0, bytes);
                writer.Write(buffer, 0, bytes);
            }

            int AudioSetup(ref IntPtr opaque, ref IntPtr format, ref uint rate, ref uint channels)
            {
                channels = (uint)waveFormat.Channels;
                rate     = (uint)waveFormat.SampleRate;
                return(0);
            }

            void DrainAudio(IntPtr data)
            {
                writer.Flush();
            }

            void FlushAudio(IntPtr data, long pts)
            {
                writer.Flush();
                waveProvider.ClearBuffer();
            }

            void ResumeAudio(IntPtr data, long pts)
            {
                outputDevice.Play();
            }

            void PauseAudio(IntPtr data, long pts)
            {
                outputDevice.Pause();
            }

            void AudioCleanup(IntPtr opaque)
            {
            }
        }
Exemplo n.º 20
0
 private void PlayMp3(string path)
 {
     if (isPlaying)
     {
         player.Stop();
         player.Dispose();
     }
     using (var FD = TagLib.File.Create(path))
     {
         if (mainOutputStream != null)
         {
             mainOutputStream.Dispose();
         }
         player = new WaveOutEvent();
         if (!File.Exists(path))
         {
         }
         else
         {
             mainOutputStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(path)); //new Mp3FileReader(path);
             volumeStream     = new WaveChannel32(mainOutputStream);
             player.Init(volumeStream);
             trackSlider.Maximum = volumeStream.Length;
             string curTimeString = mainOutputStream.TotalTime.ToString("mm\\:ss");
             time2.Text = curTimeString;
             {
                 using (var db = new Context())
                 {
                     var a = db.Audios.Where(a => a.id == selectedAudioId).FirstOrDefault();
                     a.lastPlay  = DateTime.Now;
                     a.countPlay = a.countPlay + 1;
                     db.SaveChanges();
                     trackPerformer.Text = a.Singer;
                     trackName.Text      = a.Title;
                     try
                     {
                         trackCover.Source = PlaylistNameDialog.LoadImage(FD.Tag.Pictures[0].Data.Data);
                     }
                     catch
                     {
                         string        directoryName = Path.GetDirectoryName(path);
                         DirectoryInfo di            = new DirectoryInfo(directoryName);
                         string        firstFileName = di.GetFiles().Select(fi => fi.Name).Where(x => x.Substring(x.Length - 3) == "jpg" || x.Substring(x.Length - 3) == "png" || x.Substring(x.Length - 3) == "jpeg").FirstOrDefault();
                         var           img           = new System.Windows.Media.Imaging.BitmapImage(new Uri(directoryName + @"\" + firstFileName, UriKind.Relative));
                         if (img != null && !string.IsNullOrEmpty(firstFileName))
                         {
                             directoryName     = directoryName + @"\" + firstFileName;
                             currentImage      = new System.Windows.Media.Imaging.BitmapImage(new Uri(@directoryName, UriKind.RelativeOrAbsolute));
                             trackCover.Source = currentImage;
                         }
                         else
                         {
                             currentImage      = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"404.png", UriKind.RelativeOrAbsolute));
                             trackCover.Source = currentImage;
                         }
                     }
                 }
             }
             player.Play();
             isPlaying          = true;
             trackSlider.Value  = 0;
             volumeSlider.Value = volume;
         }
         FD.Dispose();
     }
 }
Exemplo n.º 21
0
        public void InitScene()
        {
            IsDisposed = false;
            GameEnded  = false;
            gameHUD    = new GameHUD(gl);
            gameHUD.Init();
            SceneManager.HUD = gameHUD;

            // Create scene's background
            CreateBackground();

            // Create player
            PlayerObject player = new PlayerObject(new Vector2(34, 71), "Player", new Vector2(SceneManager.ScreenSize.X / 2f, 5));

            player.Animator.AddTexture("HOOK", new Bitmap("./Textures/HOOK.png"));
            player.Animator.CurrentTexture = "HOOK";
            SceneManager.AddObject(player);
            SceneManager.Player = player;

            // Create fishes
            Fish.RegisterTextures();
            Fish3.RegisterTextures();
            new Thread(new ThreadStart(CreateFishes)).Start();

            // Create bombs
            Bombs.RegisterTextures();
            new Thread(new ThreadStart(CreateBombs)).Start();

            // Create bubbles
            float bubblePos = 500;

            while (bubblePos < 17000)
            {
                CreateBubbles(new Vector2((float)this.random.NextDouble() * SceneManager.ScreenSize.X, bubblePos, SceneManager.ScreenSize.X, 0));
                bubblePos += 50 + (float)this.random.NextDouble() * 475;
            }

            // Create player's aim
            GameObject aim = new GameObject(new Vector2(40, 40), "Aim");

            aim.Animator.AddTexture("AIM", AIM_TEXTURE_ID);
            aim.Animator.CurrentTexture = "AIM";
            aim.Transform.SetPositionFn(() => {
                aim.Transform.Position = SceneManager.MousePositionInScene() - aim.Transform.Size / 2f;
            });
            SceneManager.Aim = aim;

            // Play games' song
            long position;

            try {
                position = OutputDevice.GetPosition();
            } catch {
                position = 0;
            }

            if (position == 0)
            {
                keepPlaying = true;
                OutputDevice.PlaybackStopped += SongStopped;
                OutputDevice.Init(audioFile);
                OutputDevice.Play();
            }
        }
Exemplo n.º 22
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Controls.Button button = (System.Windows.Controls.Button)sender;

                switch (button.Name)
                {
                case "Ab0rt":

                    break;

                case "IsraelNuke":

                    var text = Richy.Text;
                    if (MoonbaseCheckbox.IsChecked == true)
                    {
                        text = memetext(text);
                    }
                    //save as a sound file
                    const string abusedFile = "abusedFile.wav";
                    using (var tts = new FonixTalkEngine())
                    {
                        tts.Voice = (TtsVoice)Enum.Parse(typeof(TtsVoice), VoiceSelector.Text);


                        tts.SpeakToWavFile(abusedFile, text);
                    }

                    if (LucciHear.IsChecked == true)
                    {
                        Console.WriteLine("how the f**k ise this happen?");
                        //System.IO.File.Copy(abusedFile, "copyboy", true);
                        //playback on speaker
                        string SelectedName = abusedFile;
                        Thread thread       = new Thread(new ParameterizedThreadStart((__SelectedName) =>
                        {
                            string _SelectedName = (string)__SelectedName;
                            //https://github.com/naudio/NAudio
                            try
                            {
                                using (var audioFile = new AudioFileReader(_SelectedName))
                                {
                                    int selDevice = -1;

                                    {
                                        for (int n = -1; n < WaveOut.DeviceCount; n++)
                                        {
                                            var caps = WaveOut.GetCapabilities(n);
                                            if (caps.ProductName.StartsWith(CURRENT_SPEAKER_VALUE))
                                            {
                                                selDevice = n;
                                                break;
                                            }
                                        }
                                    }
                                    Console.WriteLine("ree+ " + selDevice);
                                    using (var outputDevice = new WaveOutEvent()
                                    {
                                        DeviceNumber = selDevice
                                    })
                                    {
                                        outputDevice.Init(audioFile);
                                        outputDevice.Volume = (float)percentagevolume;
                                        outputDevice.Play();
                                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                                        {
                                            Thread.Sleep(1000);
                                        }
                                    }
                                }
                            }
                            catch (System.Runtime.InteropServices.COMException e3)
                            { Console.WriteLine(e3); }
                        }));
                        thread.Start(SelectedName);
                    }
                    //////////
                    //now output from the sound file
                    using (var audioFile = new AudioFileReader(abusedFile))
                    {
                        int selDevice = -1;


                        {
                            Console.WriteLine("THIS SHOULD BE FIRST");
                            for (int n = -1; n < WaveOut.DeviceCount; n++)
                            {
                                var caps = WaveOut.GetCapabilities(n);
                                Console.WriteLine(caps.ProductName + ", " + CURRENT_MIC_VALUE);
                                if (caps.ProductName.StartsWith(CURRENT_MIC_VALUE))
                                {
                                    selDevice = n;
                                    break;
                                }
                            }
                        }
                        using (var outputDevice = new WaveOutEvent()
                        {
                            DeviceNumber = selDevice
                        })
                        {
                            // PressAppropriatePTTButton(true);
                            outputDevice.Init(audioFile);
                            outputDevice.Volume = (float)percentagevolume;
                            outputDevice.Play();
                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                Thread.Sleep(1000);
                            }
                            //  PressAppropriatePTTButton(false);
                        }
                    }
                    break;
                }
            }catch (Exception exception)
            {
                Log("ERROR:" + exception.Message + ": " + exception.StackTrace);
            }
        }
Exemplo n.º 23
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;

            switch (button.Name)
            {
            case "StartRecord":
            {
                if (clipper.stopbuttonisntpressed == true)
                {
                    log("its recording already idiot");
                    return;
                }
                log("manual recording started.");
                ugh = new Thread(new ThreadStart(() =>
                    {
                        string randomfilenamepls = randomnamereeee();
                        clipper.StartRecordingSpecial(randomfilenamepls);
                        clipper.recordingSpecialThread.Join();
                        log("manual recording ended. saved to " + randomfilenamepls);
                    }));
                ugh.Start();
            }
            break;

            case "EndRecord":
            {
                clipper.StopRecordingSpecial();
                ugh.Join();
                FClip clip = clipper.AddRandomCustomFileToList();
                ListBoxObject.Items.Add(clipper.AddAndMapPath(clip.fileName));
            }
            break;

            case "RecordButton":
            {
                FClip clip = clipper.AddLastXSecondsToList();
                ListBoxObject.Items.Add(clipper.AddAndMapPath(clip.fileName));
                Console.WriteLine(clip.fileName + " added.");
            }
            break;

            case "SaveButton":
                if (((string)(ListBoxObject.SelectedValue)) == null)
                {
                    Console.WriteLine("Nothing selected");
                    return;
                }
                for (int n = -1; n < WaveOut.DeviceCount; n++)
                {
                    var caps = WaveOut.GetCapabilities(n);
                    Console.WriteLine(caps.ProductName);
                }
                break;

            case "ListenButton":
            {
                if (((string)(ListBoxObject.SelectedValue)) == null)
                {
                    Console.WriteLine("Nothing selected");
                    return;
                }

                string SelectedName = (string)(ListBoxObject.SelectedValue);
                Console.WriteLine("Listening to " + SelectedName);
                Thread thread = new Thread(new ParameterizedThreadStart((__SelectedName) =>
                    {
                        string _SelectedName = (string)__SelectedName;
                        //https://github.com/naudio/NAudio
                        try
                        {
                            using (var audioFile = new AudioFileReader(clipper.GetPath(_SelectedName)))
                            {
                                int selDevice = -1;
                                for (int n = -1; n < WaveOut.DeviceCount; n++)
                                {
                                    var caps = WaveOut.GetCapabilities(n);
                                    if (caps.ProductName.Contains("Headset Earphone"))
                                    {
                                        selDevice = n;
                                        break;
                                    }
                                }
                                using (var outputDevice = new WaveOutEvent()
                                {
                                    DeviceNumber = selDevice
                                })
                                {
                                    outputDevice.Init(audioFile);
                                    outputDevice.Volume = (float)percentagevolume;
                                    outputDevice.Play();
                                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                                    {
                                        Thread.Sleep(1000);
                                    }
                                }
                            }
                        }
                        catch (System.Runtime.InteropServices.COMException e3)
                        { Console.WriteLine(e3); }
                    }));
                thread.Start(SelectedName);
            }
            break;

            case "PlayButton":
            {
                try
                {
                    if (((string)(ListBoxObject.SelectedValue)) == null)
                    {
                        Console.WriteLine("Nothing selected");
                        return;
                    }
                    string SelectedName = (string)(ListBoxObject.SelectedValue);
                    Console.WriteLine("Playing " + SelectedName);
                    Thread thread = new Thread(new ParameterizedThreadStart((__SelectedName) =>
                        {
                            string _SelectedName = (string)__SelectedName;
                            //https://github.com/naudio/NAudio

                            try
                            {
                                using (var audioFile = new AudioFileReader(clipper.GetPath(_SelectedName)))
                                {
                                    int selDevice = -1;
                                    for (int n = -1; n < WaveOut.DeviceCount; n++)
                                    {
                                        var caps = WaveOut.GetCapabilities(n);
                                        if (caps.ProductName.Contains("CABLE Input"))
                                        {
                                            selDevice = n;
                                            break;
                                        }
                                    }
                                    using (var outputDevice = new WaveOutEvent()
                                    {
                                        DeviceNumber = selDevice
                                    })
                                    {
                                        outputDevice.Init(audioFile);
                                        outputDevice.Volume = (float)percentagevolume;
                                        outputDevice.Play();
                                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                                        {
                                            Thread.Sleep(1000);
                                        }
                                    }
                                }
                            }
                            catch (System.Runtime.InteropServices.COMException e3)
                            { Console.WriteLine(e3); }
                            catch (Exception e4)
                            {
                                Console.WriteLine(e4);
                            }
                        }));
                    thread.Start(SelectedName);
                    KillableThreads.Add(thread);
                }catch (Exception e2)
                {
                    Console.WriteLine(e2.StackTrace);
                }
            }
            break;

            case "KillButton":
                for (int i = 0; i < KillableThreads.Count; i++)
                {
                    KillableThreads[i].Abort();
                }
                KillableThreads.Clear();
                break;

            case "CloseButton":
                try
                {
                    SetDeviceToAudio2();
                }
                catch { }
                try
                {
                    chromeDriver.Close();
                }
                catch { }
                Environment.Exit(0);
                break;

            case "LoadButton":
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Multiselect = true;
                ofd.DefaultExt  = ".wav";
                ofd.Filter      = "soundfiles (.wav)|*.wav";

                if (ofd.ShowDialog() == true)
                {
                    string[] fileNames = new string[ofd.FileNames.Length];
                    string[] pathNames = new string[ofd.FileNames.Length];
                    for (int i = 0; i < fileNames.Length; i++)
                    {
                        fileNames[i] = System.IO.Path.GetFileName(ofd.FileNames[i]);
                        pathNames[i] = System.IO.Path.GetDirectoryName(ofd.FileName);
                        ListBoxObject.Items.Add(clipper.AddAndMapPath(pathNames[i] + "\\" + fileNames[i]));
                        Console.WriteLine("Loaded " + pathNames[i] + "\\" + fileNames[i] + ".");
                    }
                }
                break;

            case "RenameButton":
            {
                if (((string)(ListBoxObject.SelectedValue)) == null)
                {
                    Console.WriteLine("Nothing selected");
                    return;
                }
                string SelectedName = (string)(ListBoxObject.SelectedValue);

                RetardBox.Visibility = Visibility.Visible;

                RenamePath      = clipper.GetPath(SelectedName);
                RenameShortName = String.Copy(SelectedName);

                string dispName = "";
                if (SelectedName.StartsWith(":") && SelectedName.Length != 1)
                {
                    dispName = SelectedName.Substring(1);
                }
                else
                {
                    dispName = SelectedName;
                }


                NameInputHandle.Text = dispName;
            }
            break;

            case "YesButton":

                string textToFix = NameInputHandle.Text;
                //remove extension from text if there is one
                if (textToFix.Contains("."))
                {
                    textToFix = textToFix.Substring(0, textToFix.IndexOf('.'));
                }

                //save the old extension
                string correctExtensionPlusDot = RenamePath.Substring(RenamePath.IndexOf('.'));
                if (textToFix.StartsWith(":"))
                {
                    return;
                }

                //append the old extension to the new text
                string renamedPath = RenamePath.Substring(0, RenamePath.LastIndexOf("\\"))
                                     + "\\" + textToFix + correctExtensionPlusDot;
                try
                {
                    System.IO.File.Move(RenamePath, renamedPath);

                    //now fix ui to reflect changes
                    ListBoxObject.Items[ListBoxObject.SelectedIndex] = clipper.Rename(RenamePath, renamedPath,
                                                                                      RenameShortName.StartsWith(":"), textToFix + correctExtensionPlusDot);
                }
                catch (Exception ere3)
                {
                    Console.Error.WriteLine("crashmessage=" + ere3.Message + "\r\n" + ere3.StackTrace);
                }
                RetardBox.Visibility = Visibility.Hidden;

                break;

            case "NoButton":
                RetardBox.Visibility = Visibility.Hidden;
                break;
            }
        }
Exemplo n.º 24
0
 private void TheMouseDown(object sender, MouseEventArgs e)
 {
     player.Play();
 }
Exemplo n.º 25
0
 public void playSound()
 {
     resetAudioPlayer();
     output.Play();
 }
Exemplo n.º 26
0
 /// <summary>
 /// Begins playing audio from current track position
 /// </summary>
 public void Play()
 {
     waveOutEvent.Play();
 }
Exemplo n.º 27
0
        private void Play_Click(object sender, RoutedEventArgs e)
        {
            UndertaleSound sound = DataContext as UndertaleSound;

            if ((sound.Flags & UndertaleSound.AudioEntryFlags.IsEmbedded) != UndertaleSound.AudioEntryFlags.IsEmbedded &&
                (sound.Flags & UndertaleSound.AudioEntryFlags.IsCompressed) != UndertaleSound.AudioEntryFlags.IsCompressed)
            {
                try
                {
                    string filename;
                    if (!sound.File.Content.Contains("."))
                    {
                        filename = sound.File.Content + ".ogg";
                    }
                    else
                    {
                        filename = sound.File.Content;
                    }
                    string audioPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName((Application.Current.MainWindow as MainWindow).FilePath), filename);
                    if (File.Exists(audioPath))
                    {
                        switch (System.IO.Path.GetExtension(filename).ToLower())
                        {
                        case ".wav":
                            wavReader = new WaveFileReader(audioPath);
                            InitAudio();
                            waveOut.Init(wavReader);
                            waveOut.Play();
                            break;

                        case ".ogg":
                            oggReader = new VorbisWaveReader(audioPath);
                            InitAudio();
                            waveOut.Init(oggReader);
                            waveOut.Play();
                            break;

                        case ".mp3":
                            mp3Reader = new Mp3FileReader(audioPath);
                            InitAudio();
                            waveOut.Init(mp3Reader);
                            waveOut.Play();
                            break;

                        default:
                            throw new Exception("Unknown file type.");
                        }
                    }
                    else
                    {
                        throw new Exception("Failed to find audio file.");
                    }
                } catch (Exception ex)
                {
                    waveOut = null;
                    MessageBox.Show("Failed to play audio!\r\n" + ex.Message, "Audio failure", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                return;
            }

            UndertaleEmbeddedAudio target;

            if (sound.GroupID != 0 && sound.AudioID != -1)
            {
                try
                {
                    string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName((Application.Current.MainWindow as MainWindow).FilePath), "audiogroup" + sound.GroupID + ".dat");
                    if (File.Exists(path))
                    {
                        if (loadedPath != path)
                        {
                            loadedPath = path;
                            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                            {
                                audioGroupData = UndertaleIO.Read(stream, warning =>
                                {
                                    throw new Exception(warning);
                                });
                            }
                        }

                        target = audioGroupData.EmbeddedAudio[sound.AudioID];
                    }
                    else
                    {
                        throw new Exception("Failed to find audio group file.");
                    }
                } catch (Exception ex)
                {
                    waveOut = null;
                    MessageBox.Show("Failed to play audio!\r\n" + ex.Message, "Audio failure", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            else
            {
                target = sound.AudioFile;
            }

            if (target != null)
            {
                if (target.Data.Length > 4)
                {
                    try
                    {
                        if (target.Data[0] == 'R' && target.Data[1] == 'I' && target.Data[2] == 'F' && target.Data[3] == 'F')
                        {
                            wavReader = new WaveFileReader(new MemoryStream(target.Data));
                            InitAudio();
                            waveOut.Init(wavReader);
                            waveOut.Play();
                        }
                        else if (target.Data[0] == 'O' && target.Data[1] == 'g' && target.Data[2] == 'g' && target.Data[3] == 'S')
                        {
                            oggReader = new VorbisWaveReader(new MemoryStream(target.Data));
                            InitAudio();
                            waveOut.Init(oggReader);
                            waveOut.Play();
                        }
                        else
                        {
                            MessageBox.Show("Failed to play audio!\r\nNot a WAV or OGG.", "Audio failure", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                    catch (Exception ex)
                    {
                        waveOut = null;
                        MessageBox.Show("Failed to play audio!\r\n" + ex.Message, "Audio failure", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            else
            {
                MessageBox.Show("Failed to play audio!\r\nNo options for playback worked.", "Audio failure", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 28
0
 // Starts the stream
 public void Play()
 {
     wo.Play();
 }
Exemplo n.º 29
0
        /// ------------------------------------------------------------------------------------
        public void Play(TimeSpan playbackStartTime, TimeSpan playbackEndTime)
        {
            if (_waveOut != null && _waveOut.PlaybackState == PlaybackState.Playing)
            {
                throw new InvalidOperationException("Can't call play while playing.");
            }

            if (_playbackStream == null || (_playbackStream.WaveFormat.BitsPerSample == 32 &&
                                            _playbackStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat))
            {
                return;
            }

            SetCursor(playbackStartTime);

            _playbackRange = new TimeRange(playbackStartTime, playbackEndTime);

            if (_playbackRange.Start < TimeSpan.Zero)
            {
                _playbackRange.Start = TimeSpan.Zero;
            }

            if (_playbackRange.DurationSeconds.Equals(0))
            {
                _playbackRange.End = WaveStream.TotalTime;
                EnsureTimeIsVisible(_playbackRange.Start);
            }
            else
            {
                EnsureTimeIsVisible(_playbackRange.Start, _playbackRange, true, true);
            }

            AudioUtils.NAudioExceptionThrown += HandleNAudioExceptionThrown;

            var waveOutProvider = new SampleChannel(_playbackRange.End == TimeSpan.Zero || _playbackRange.End == WaveStream.TotalTime ?
                                                    new WaveSegmentStream(_playbackStream, playbackStartTime) :
                                                    new WaveSegmentStream(_playbackStream, playbackStartTime, playbackEndTime - playbackStartTime));

            waveOutProvider.PreVolumeMeter += HandlePlaybackMetering;

            try
            {
                _waveOut = new WaveOutEvent();
                _waveOut.DesiredLatency  = 500;
                _waveOut.NumberOfBuffers = 5;
                _waveOut.Init(new SampleToWaveProvider(waveOutProvider));
                _waveOut.PlaybackStopped += WaveOutOnPlaybackStopped;
                _waveOut.Play();
                OnPlaybackStarted(playbackStartTime, playbackEndTime);
            }
            catch (MmException exception)
            {
                if (_waveOut != null)
                {
                    _waveOut.Dispose();
                }
                _waveOut = null;
                Logger.WriteEvent("Exception in WaveControllerbasic.Play:\r\n{0}", exception.ToString());
                DesktopAnalytics.Analytics.ReportException(exception);
                //  throw;
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// NIE KURWA JEGO MAĆ RUSZAĆ TEGO. CHUJ WIE JAK TO DZIAŁA, ALE ,,U MNIE DZIAŁO"
 /// </summary>
 public static void Resume()
 {
     woe.Play();
     Source.Global.PlayerTaskPaused = false;
 }