Ejemplo n.º 1
0
        public void PlayBackgroundMusic(int mfxID)
        {
            if (mfxID < 1 || mfxID >= m_music.Count)
            {
                throw new ArgumentOutOfRangeException("mfxID", "The MFX id is out of range. Use the 1-based index that matches the number in the file name.");
            }

            Action _func = () =>
            {
                m_songPlayer.Stop();
                m_songPlayer.Close();
                m_songPlayer.Open(m_music[mfxID - 1]);
                m_songPlayer.Play();
            };

            //when changing the map, the background music will be played from a different thread than the main
            //	one since it is all being done in a callback from the received network data. This requires a
            //	dispatcher to invoke the song change on the m_songPlayer, otherwise an exception is thrown because
            //	the thread does not 'own' the m_songPlayer object.
            if (m_dispatcher.Thread != Thread.CurrentThread)
            {
                m_dispatcher.BeginInvoke(_func);
            }
            else
            {
                _func();
            }
        }
Ejemplo n.º 2
0
        private void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = "wav files (*.wav)|*.wav|All files (*.*)|*.*";
            if (dialog.ShowDialog() == true)
            {
                if (player.Source != null)
                {
                    player.Close();
                }
                player.Open(new Uri(dialog.FileName, UriKind.Absolute));
            }
        }
Ejemplo n.º 3
0
        static double GetPodcastLength(string uri)
        {
            MediaPlayer player = new MediaPlayer();
            //Something is wrong. It dies here.
            player.Open(new Uri(uri, UriKind.Absolute));

            double returnLength = 0;

            if (player.NaturalDuration.HasTimeSpan)
            {
                returnLength = player.NaturalDuration.TimeSpan.TotalSeconds;
            }

            player.Close();

            return returnLength;
        }
        public static void CaptureScreen(Uri source, Dictionary<TimeSpan, object> captureList, double scale, CaptureWorkerDelegate finalWorkerPrimary, CaptureWorkerDelegate finalWorkerThumbnail)
        {
            var mutexLock = new Mutex(false, source.GetHashCode().ToString());
            mutexLock.WaitOne();

            var player = new MediaPlayer { Volume = 0, ScrubbingEnabled = true };

            player.Open(source);
            player.Pause();
            foreach (var pair in captureList)
            {
                var timeSpan = pair.Key;
                var state = pair.Value;

                player.Position = timeSpan;
                Thread.Sleep(1000);

                var width = player.NaturalVideoWidth;
                var height = player.NaturalVideoHeight;

                var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
                var dv = new DrawingVisual();

                using (DrawingContext dc = dv.RenderOpen())
                    dc.DrawVideo(player, new Rect(0, 0, width, height));

                rtb.Render(dv);
                var frame = BitmapFrame.Create(rtb).GetCurrentValueAsFrozen();
                if (finalWorkerPrimary != null)
                    finalWorkerPrimary(frame as BitmapFrame, state);

                if (scale > 0 && finalWorkerThumbnail != null)
                {
                    var thumbnailFrame =
                        BitmapFrame.Create(new TransformedBitmap(frame as BitmapSource, new ScaleTransform(scale, scale))).
                            GetCurrentValueAsFrozen();
                    var encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(thumbnailFrame as BitmapFrame);

                    finalWorkerThumbnail(thumbnailFrame as BitmapFrame, state);
                }
            }
            player.Close();
            mutexLock.ReleaseMutex();
        }
Ejemplo n.º 5
0
        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Up || e.Key == Key.Down)//si usa las flechas
            {
                if (listLecciones.Items.Count != 0)
                {
                    if (listLecciones.SelectedItem != null)
                    {
                        voz.hablarAsync("Lección " + ((elementoDeLista)listLecciones.SelectedItem).cajaTexto.Text);

                        MediaPlayer reproductor = new MediaPlayer();
                        reproductor.Close();
                        string rutaInicial = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + @"\Recursos\Sonidos\";

                        if (AdminEstadísticas.LecciónTerminada(idUsr, idActividad, int.Parse(((elementoDeLista)listLecciones.SelectedItem).cajaTexto.Text)))
                        {
                            if (File.Exists(rutaInicial + "hecho.wav"))
                            {
                                reproductor.Open(new Uri(rutaInicial + "hecho.wav"));
                                reproductor.Play();
                            }
                        }
                        else
                        {
                            if (File.Exists(rutaInicial + "noHecha.wav"))
                            {
                                reproductor.Open(new Uri(rutaInicial + "noHecha.wav"));
                                reproductor.Play();
                            }
                        }
                    }
                }
            }

            if (e.Key == Key.RightCtrl || e.Key == Key.LeftCtrl)//si usa las flechas
            {
                voz.callar();
            }
        }
Ejemplo n.º 6
0
        protected override void CreateImage()
        {
            string filename = FileSourceHelper.ResolveFileName(SourceFileName, Site, DesignMode);

            MediaPlayer mediaPlayer = new MediaPlayer
            {
                ScrubbingEnabled = true
            };

            object monitorObject = new object();
            mediaPlayer.MediaOpened += (sender, e) => Monitor.Exit(monitorObject);

            Monitor.Enter(monitorObject);
            mediaPlayer.Open(new Uri(filename));
            Monitor.Wait(monitorObject, 1000);

            int width = mediaPlayer.NaturalVideoWidth;
            int height = mediaPlayer.NaturalVideoHeight;

            // Seek to specified time.
            mediaPlayer.BufferingEnded += (sender, e) => Monitor.Exit(monitorObject);
            Monitor.Enter(monitorObject);
            mediaPlayer.Position = SnapshotTime;
            Monitor.Wait(monitorObject, 1000);

            DrawingVisual dv = new DrawingVisual();
            DrawingContext dc = dv.RenderOpen();
            dc.DrawVideo(mediaPlayer, new System.Windows.Rect(0, 0, width, height));
            dc.Close();

            RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(width, height);
            rtb.Render(dv);
            Bitmap = new FastBitmap(rtb);

            mediaPlayer.Close();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 视频截取第一帧
        /// </summary>
        /// <param name="videopath">要截屏的视频路径</param>
        /// <param name="savepath">要把截屏保存到得路径</param>
        /// <param name="rect">截屏所得图片框大小</param>
        public static void GetVideoThumb(string videopath, string savepath, Rect rect)
        {
            //打开视频
            MediaPlayer _player = new MediaPlayer();
            _player.Volume = 0;
            _player.Open(new Uri(videopath));
            _player.Play();

            //截取视频第一帧
            Thread.Sleep(1300);
            RenderTargetBitmap target = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 1 / 100, 1 / 100, PixelFormats.Pbgra32);
            DrawingVisual visual = new DrawingVisual();
            DrawingContext context = visual.RenderOpen();
            context.DrawVideo(_player, new Rect(0, 0, (int)rect.Width, (int)rect.Height));
            context.Close();

            target.Render(visual);

            //移除视频
            _player.Stop();
            _player.Position = TimeSpan.FromSeconds(0);
            _player.Close();
            _player = null;

            //保存第一帧
            BitmapEncoder encoder = new TiffBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(target));

            FileStream fs = new FileStream(savepath, FileMode.Create);
            encoder.Save(fs);
            fs.Close();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the play time for a music file.
        /// </summary>
        /// <param name="fileName">
        /// The full path of the music file e.g. "C:\Users\Public\Music\song.mp3".
        /// </param>
        /// <returns>
        /// The file play time in seconds (0 if failed).
        /// </returns>
        public static Primitive MusicPlayTime(Primitive fileName)
        {
            if (!System.IO.File.Exists(fileName))
            {
                Utilities.OnFileError(Utilities.GetCurrentMethod(), fileName);
                return 0;
            }
            try
            {
                MediaPlayer mediaPlayer = new MediaPlayer();
                Uri uri = new Uri(fileName);
                mediaPlayer.Open(uri);
                //Wait for the player to open the file (up to 1 sec)
                int iCount = 0;
                while (!mediaPlayer.NaturalDuration.HasTimeSpan && iCount < 100)
                {
                    Thread.Sleep(10);
                    iCount++;
                }
                Duration duration = mediaPlayer.NaturalDuration;
                int sec = duration.TimeSpan.Minutes * 60 + duration.TimeSpan.Seconds + 1; //Round up
                mediaPlayer.Close();
                return sec;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }

            return 0;
        }
Ejemplo n.º 9
0
 private void SeekToNextThumbnailPosition(MediaPlayer mediaPlayer)
 {
     // If more frames remain to capture...
       if (0 < _positionsToThumbnail.Count)
       {
     // Seek to next position and start watchdog timer
     mediaPlayer.Position = _positionsToThumbnail.Dequeue();
     _watchdogTimer.Start();
       }
       else
       {
     // Done; close media file and stop processing
     mediaPlayer.Close();
     //framePixels = null;
     //previousFramePixels = null;
     SetProcessing(this, false);
       }
 }
Ejemplo n.º 10
0
        private void GetDuration()
        {
            try
            {
                MediaPlayer mp = new MediaPlayer();
                mp.Open(TrackUri);
                int cnt = 0; // protect neverending loop
                while ((!mp.NaturalDuration.HasTimeSpan) && (cnt < 10000))
                    Thread.Sleep(10);
                if (mp.NaturalDuration.HasTimeSpan)
                    duration = mp.NaturalDuration.TimeSpan;
                mp.Close();

                if ((duration != TimeSpan.Zero) && (PropertyChanged != null))
                    PropertyChanged(this, new PropertyChangedEventArgs("Duration"));
            }
            catch { }
        }
Ejemplo n.º 11
0
        //void animarTeclado(Key teclaApretada)
        //{
        //    switch (teclaApretada)
        //    {
        //        case Key.A:
        //            teclado.BeginStoryboard(tecla);
        //            break;
        //        case Key.B:
        //            teclado.b.FontSize = 24;
        //            break;
        //    }
        //}

        private void ventana_KeyDown(object sender, KeyEventArgs e)
        {
            
            string textoParaHablar;

            ResultadoActividad result = new ResultadoActividad();
            string letra = e.Key.ToString().ToLower();

            try
            {
                if (e.Key == Key.RightShift || e.Key == Key.LeftShift) //si se aprieta el shift
                    swShiftActivo = true;

                if (e.Key == Key.RightAlt || e.Key == Key.LeftAlt) //si se aprieta el alt
                    swAltActivo = true;

                if (e.Key == Key.Capital)
                    if (e.IsToggled)
                        voz.hablarAsync("Bloqueador de mayúsculas activado");
                    else
                        voz.hablarAsync("Bloqueador de mayúsculas desactivado");

                if (e.Key == Key.NumLock)
                    if (e.IsToggled)
                        voz.hablarAsync("Bloqueador de números activado");
                    else
                        voz.hablarAsync("Bloqueador de números desactivado");

                bool swArribaEñe = false;
                if (adminPref.lugarDelAcento == lugarAcento.arribaDeLaEñe)
                    swArribaEñe = true;

                letra = auxLetras.corregirCarácter(letra, swShiftActivo, swAltActivo, swArribaEñe);

                if (auxLetras.esCarácterLegible(letra))
                {
                    if (letra == "space") letra = " ";
                    result = adminAct.ingresarLetraUsuario(letra.ToString());
                    if (result.continúaActividad)
                    {
                        if (result.letraCorrecta && !result.esperarPorAcento) //si la letra es correcta pero no hay que esperar por una vocal por el acento
                        {
                            posiciónCarácterActualEnPalabra++;
                        }
                    }
                    else
                    {
                        MediaPlayer reproductor = new MediaPlayer(); //se reproduce el sonido
                        reproductor.Close();
                        string rutaInicial = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + @"\Recursos\Sonidos\";
                        if (File.Exists(rutaInicial + "finActividad.wav"))
                        {
                            reproductor.Open(new Uri(rutaInicial + "finActividad.wav"));
                            reproductor.Play();
                        }

                        adminEst.guardarEstadísticas(idUsuario, idActividad, adminAct.IdLecciónActual); //se guarda la estadística

                        string mensaje = "Muy bien! Terminaste todas las lecciones de esta actividad para practicar ";
                        switch (adminAct.TipoActividad)
                        {
                            case tipoActividad.palabras:
                                mensaje += " palabras";
                                break;
                            case tipoActividad.sílabas:
                                mensaje += " sílabas";
                                break;
                            case tipoActividad.letras:
                                mensaje += " letras";
                                break;
                            case tipoActividad.números:
                                mensaje += " números";
                                break;
                            case tipoActividad.símbolos:
                                mensaje += " símbolos";
                                break;
                        }

                        mensaje += "!. Ahora vas a ir al menú principal así podés elegir otra actividad para seguir practicando";

                        voz.hablar(mensaje);


                        //Lecciones ventanaAct = new Lecciones(rutaAct, tipoAct, idUsuario);
                        //ventanaAct.swVolviendo = true;
                        //ventanaAct.Show();
                        //this.Close();
                        Actividades ventanaAct = new Actividades(idUsuario);
                        ventanaAct.swVolviendo = true;
                        ventanaAct.Show();
                        this.Close();
                        return;
                    }

                    textoParaHablar = elegirMensajeParaHablar(result);

                    if (result.letraCorrecta) //se cargan las estadísticas
                        adminEst.cargarLetraAcierto(char.Parse(letra));
                    else
                        adminEst.cargarLetraError(char.Parse(letra));

                    medidor1.actualizarGráfico(adminEst.estadística.aciertos, adminEst.estadística.errores, miPincel); //se actualiza el medidor


                    if (result.tiempoAgotado)
                        textoParaHablar += ", tiempo agotado";


                    if (adminAct.swhayPalabraNueva)
                        cargarPalabra();

                    if (adminAct.swhayLecciónNueva)
                        adminEst.guardarEstadísticas(idUsuario, idActividad, adminAct.IdLecciónAnterior); //cambiar 1,1 por el número de la act y de la lecc

                    e.Handled = true; //se evita que se procese la tecla en el sistema, esto por los acentos y diéresis
                    //se actualizan las estadísticas
                    actualizarTxtEstadísticas();

                    animarTexto();

                    voz.hablarAsync(textoParaHablar);
                }

                if (e.Key == Key.Escape) //si aprieta escape, volver a las lecciones
                {
                    Lecciones ventanaAct = new Lecciones(rutaAct, tipoAct, idUsuario, idActividad);
                    ventanaAct.swVolviendo = true;
                    ventanaAct.Show();
                    this.Close();
                }

                if (e.Key == Key.F1) //F1, recordar texto actual a escribir y lo ya escrito
                {
                    recordarPalabraActual();
                }

                if (e.Key == Key.F2) //F2, deletrear palabra
                {
                    deletrearPalabraActual();
                }

                if (e.Key == Key.F3) //F3, ayuda de qué dedo apretar
                {
                    char miLetra;
                    char.TryParse(adminAct.LetraActualLección, out miLetra);
                    voz.hablarAsync(elegirAyudaQuéDedoUsar(miLetra));
                }

                if (e.Key == Key.F4) //F4, cambia el estado de visibilidad del teclado en pantalla
                {
                    if (miTeclado.IsVisible)
                    {
                        miTeclado.Visibility = Visibility.Hidden;
                        txtTexto.Margin = new Thickness(53, this.Width / 4, 49, 0);
                        voz.hablarAsync("Ocultando el teclado en pantalla");
                    }
                    else
                    {
                        miTeclado.Visibility = Visibility.Visible;
                        txtTexto.Margin = new Thickness(53, 36, 49, 0);
                        voz.hablarAsync("Haciendo visible el teclado en pantalla");
                    }
                }

                if (e.Key == Key.F5) //F5, cambiar el acento entre la derecha de la eñe y arriba de la misma
                {
                    if (adminPref.lugarDelAcento == lugarAcento.arribaDeLaEñe)
                    {
                        adminPref.lugarDelAcento = lugarAcento.derechaDeLaEñe;
                        voz.hablarAsync("Configurando el acento agudo a la derecha de la eñe");
                    }
                    else
                    {
                        adminPref.lugarDelAcento = lugarAcento.arribaDeLaEñe;
                        voz.hablarAsync("Configurando el acento agudo arriba y a la derecha de la eñe");
                    }
                }

                if (e.Key == Key.F6) //F6, lee las estadísticas
                {
                    actualizarMensajeEstadísticasVoz();
                }

                if (e.Key == Key.F9) //F9, abre el editor de actividades
                {
                    abrirActividades();
                }

                if (e.Key == Key.F8) //F8, abre el estadísticas
                {
                    abrirEstadísticas();
                }

                if (e.Key == Key.F12) //F12, abre las preferencias
                {
                    abrirPreferencias();
                }

                if (e.Key == Key.RightCtrl || e.Key == Key.LeftCtrl)//si usa las flechas
                {
                    voz.callar();
                }

                //e.Handled = true; //se evita que se procese la tecla en el sistema, esto por los acentos, diéresis y efes
            }
            catch (Exception ex)
            {
                MessageBox.Show("Para enviar al desarrollador. Mensaje del error: " + ex.Message);
            }
        }
Ejemplo n.º 12
0
        private void endMediaPlayer(ref MediaPlayer player)
        {
            foreach (var entry in mpDictionary)
            {
                if (entry.Value != null && entry.Value.mediaPlayer == player)
                {
                    if (MainWindow.activeSkeletons.ContainsKey(mpDictionary[entry.Key].skeleton))
                    {
                        removeWallInteractionVisual(MainWindow.activeSkeletons[mpDictionary[entry.Key].skeleton], entry.Value.box);
                    }

                    mpDictionary[entry.Key] = null;
                    return;
                }
            }

            player.Close();

            player.MediaFailed -= mediaPlayer_MediaFailed;
            player.MediaEnded -= wallOfSound_MediaEnded;
        }
Ejemplo n.º 13
0
        private void SetSound(MediaPlayer player, AudioVisual audioVisual)
        {
            player.Close();
            if (audioVisual.Sound != null)
            {
                if ( player == SceneSoundPlayer )
                {
                    player.Volume = 0.25;
                }
                else if ( player == EffectSoundPlayer )
                {
                    player.Volume = 1;
                }

                player.Open(audioVisual.Sound);
                player.Play();
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get song's length
        /// </summary>
        /// <param name="filename">Path to the file</param>
        /// <returns>string with the number of </returns>
        private int GetMp3Length(string filename, ref string length)
        {
            int totalSeconds = 0;
            MediaPlayer player = new MediaPlayer();
            Uri path = new Uri(@filename);
            player.Open(path);

            Thread.Sleep(3000);
            Duration duration = player.NaturalDuration;

            if (duration.HasTimeSpan)
            {
                length = player.NaturalDuration.TimeSpan.Minutes.ToString() + ":";
                if (player.NaturalDuration.TimeSpan.Seconds < 10)
                    length += "0";
                length += player.NaturalDuration.TimeSpan.Seconds.ToString();
                totalSeconds = (int)Math.Round(player.NaturalDuration.TimeSpan.TotalSeconds, 0);
            }
            player.Close();
            return totalSeconds;
        }
Ejemplo n.º 15
0
        public async void Initialize()
        {
            try
            {
                radio = await Minorhythm.Load();
            }
            catch (TypeInitializationException)
            {
                Messenger.Raise(new InformationMessage
                    ("radio minorhythm から情報を読み込めませんでした。",
                    "エラー",
                    MessageBoxImage.Error,
                    "LoadError"));
                return;
            }
            if (radio == null)
            {
                await Messenger.RaiseAsync(new InformationMessage
                    ("ネットワーク接続が無効です。",
                    "エラー",
                    MessageBoxImage.Error,
                    "NetoworkError"));
                return;
            }
            RaisePropertyChanged("Radio");
            ToggleCornersCommand.RaiseCanExecuteChanged();
            ToggleThemeSongCommand.RaiseCanExecuteChanged();

            player = new MediaPlayer();
            player.BufferingStarted += (s, e) => PlayerState = State.バッファ中;
            player.BufferingEnded += (s, e) => PlayerState = State.再生中;
            player.MediaOpened += (s, e) => IsInitializedRadio = true;
            player.MediaEnded += (s, e) =>
            {
                player.Close();
                PlayerState = State.停止中;
            };
            playImageAddress = "../Resources/Play.png";
            pauseImageAddress = "../Resources/Pause.png";
            SelectedContent = radio.Contents.First();
            seakTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(100),
                                            DispatcherPriority.DataBind,
                                            (s, e) => { RaisePropertyChanged("PlayingTime"); RaisePropertyChanged("SeakPosition"); },
                                            DispatcherHelper.UIDispatcher);
            seakTimer.Start();
        }
Ejemplo n.º 16
0
        private ImageSource GetBitmapSource(LoadImageRequest loadTask, DisplayOptions loadType)
        {
            Image image = loadTask.Image;
            object source = loadTask.Source;
            ImageSource imageSource = null;

            if (source != null)
            {
                Stream imageStream = null;

                SourceType sourceType = SourceType.LocalDisk;

                image.Dispatcher.Invoke(new ThreadStart(delegate
                {
                    sourceType = Loader.GetSourceType(image);
                }));

                try
                {
                    if (loadType != DisplayOptions.VideoPreview)
                    {
                        if (loadTask.Stream == null)
                        {
                            ILoader loader = LoaderFactory.CreateLoader(sourceType);
                            imageStream = loader.Load(source);
                            loadTask.Stream = imageStream;
                        }
                        else
                        {
                            imageStream = new MemoryStream();
                            loadTask.Stream.Position = 0;
                            loadTask.Stream.CopyTo(imageStream);
                            imageStream.Position = 0;
                        }
                    }
                    else if (sourceType == SourceType.ZipFile)
                    {
                        throw new InvalidOperationException("Can't load video preview from zip file.");
                    }
                }
                catch (Exception) { }

                if (imageStream != null || loadType == DisplayOptions.VideoPreview)
                {
                    try
                    {
                        if (loadType == DisplayOptions.Preview)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            int rotation = GetRotation(bitmapFrame.Metadata as BitmapMetadata);

                            if (bitmapFrame.Thumbnail != null)
                            {
                                BitmapSource src = bitmapFrame.Thumbnail;
                                // crop black bars if necessary
                                double ratio = (double)bitmapFrame.PixelWidth / bitmapFrame.PixelHeight;
                                double thumbRatio = (double)src.PixelWidth / src.PixelHeight;
                                if (Math.Abs(ratio - thumbRatio) >= 0.01)
                                {
                                    if (ratio > thumbRatio) // crop top/bottom
                                    {
                                        int newHeight = (int)(src.PixelWidth / ratio);
                                        int top = (src.PixelHeight - newHeight) / 2;
                                        src = new CroppedBitmap(src, new Int32Rect(0, top, src.PixelWidth, newHeight));
                                    }
                                    else // crop left/right
                                    {
                                        int newWidth = (int)(src.PixelHeight * ratio);
                                        int left = (src.PixelWidth - newWidth) / 2;
                                        src = new CroppedBitmap(src, new Int32Rect(left, 0, newWidth, src.PixelHeight));
                                    }
                                }

                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = src;
                                TransformGroup transformGroup = new TransformGroup();
                                // rotate according to metadata
                                transformGroup.Children.Add(new RotateTransform(rotation));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();
                                imageSource = thumbnail;
                            }
                            else // Preview it is not embedded into the file
                            {
                                // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = bitmapFrame as BitmapSource;

                                // we'll make a reasonable sized thumnbail with a height of 240
                                int pixelH = bitmapFrame.PixelHeight;
                                int pixelW = bitmapFrame.PixelWidth;
                                int decodeH = 240;
                                int decodeW = (pixelW * decodeH) / pixelH;
                                double scaleX = decodeW / (double)pixelW;
                                double scaleY = decodeH / (double)pixelH;
                                TransformGroup transformGroup = new TransformGroup();
                                transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
                                transformGroup.Children.Add(new RotateTransform(rotation));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();

                                // this will disconnect the stream from the image completely ...
                                WriteableBitmap writable = new WriteableBitmap(thumbnail);
                                writable.Freeze();
                                imageSource = writable;
                            }
                        }
                        else if (loadType == DisplayOptions.Combined || loadType == DisplayOptions.FullResolution)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            int rotation = GetRotation(bitmapFrame.Metadata as BitmapMetadata);

                            TransformedBitmap bitmapImage = new TransformedBitmap();
                            bitmapImage.BeginInit();
                            bitmapImage.Source = bitmapFrame as BitmapSource;
                            TransformGroup transformGroup = new TransformGroup();
                            transformGroup.Children.Add(new RotateTransform(rotation));
                            bitmapImage.Transform = transformGroup;
                            bitmapImage.EndInit();

                            WriteableBitmap writable = new WriteableBitmap(bitmapImage);
                            writable.Freeze();

                            imageSource = writable;
                        }
                        else if (loadType == DisplayOptions.VideoPreview)
                        {
                            var player = new MediaPlayer { Volume = 0, ScrubbingEnabled = true };

                            Uri uri;
                            if (loadTask.Source is string)
                                uri = new Uri(loadTask.Source as string);
                            else if (loadTask.Source is Uri)
                                uri = loadTask.Source as Uri;
                            else
                                throw new InvalidOperationException();

                            player.Open(uri);
                            player.Pause();
                            player.Position = new TimeSpan(0, 0, 20); // go to 20 seconds (if the video is shorter, a black image will be captured)

                            Thread.Sleep(1000);

                            int i = 0;
                            while (i < 10 && (player.NaturalDuration.TimeSpan.TotalSeconds* player.BufferingProgress) <= 20)
                            {
                                Thread.Sleep(100);
                                i++;
                            }

                            var pixelW = player.NaturalVideoWidth;
                            var pixelH = player.NaturalVideoHeight;

                            int decodeH = 240;
                            int decodeW = (pixelW * decodeH) / pixelH;

                            var rtb = new RenderTargetBitmap(decodeW, decodeH, 96, 96, PixelFormats.Pbgra32);
                            DrawingVisual dv = new DrawingVisual();

                            using (DrawingContext dc = dv.RenderOpen())
                                dc.DrawVideo(player, new Rect(0, 0, decodeW, decodeH));

                            rtb.Render(dv);
                            imageSource = (ImageSource)BitmapFrame.Create(rtb).GetCurrentValueAsFrozen();
                            player.Close();
                        }
                    }
                    catch (Exception) { }
                }

                if (imageSource == null)
                {
                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, true);
                    }));
                }
                else
                {
                    imageSource.Freeze();

                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, false);
                    }));
                }
            }
            else
            {
                image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Loader.SetErrorDetected(image, false);
                }));
            }

            return imageSource;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 获取视频和图片的原始尺寸
        /// </summary>
        /// <param name="mediaArray"></param>
        private void GetMediaSize(string[] mediaArray)
        {
            MediaPlayer player = new MediaPlayer();
            player.IsMuted = true;
            player.Open(new Uri(mediaArray[MediaNum]));//添加计时,失败则重新加载
            bool isOpened = false;
            DispatcherTimer dt = new DispatcherTimer();
            dt.Interval = TimeSpan.FromSeconds(5);
            dt.Start();
            dt.Tick += delegate
            {
                if (!isOpened)//5秒内未能成功打开,重新加载资源
                {
                    player.Close();
                    GetMediaSize(mediaArray);
                }
                dt.Stop();
            };
            player.MediaOpened += (s, e) =>
            {
                ImportValue = MediaNum + 1;
                MediaPlayer myPlayer = s as MediaPlayer;
                Console.WriteLine("Num={0}:({1},{2})", MediaNum, myPlayer.NaturalVideoWidth, myPlayer.NaturalVideoHeight);
                SizeList.Add(new Size(myPlayer.NaturalVideoWidth, myPlayer.NaturalVideoHeight));
                myPlayer.Close();
                MediaNum++;
                isOpened = true;
                dt.Stop();
                if (MediaNum < mediaArray.Length)
                {
                    GetMediaSize(mediaArray);
                }
                else
                {

                    BarGo();
                }
            };
            player.MediaFailed += (s1, e1) =>
            {
                dt.Stop();
                MessageBox.Show("资源格式不支持(只支持图片与视频)或网络资源不存在,导入失败。");
            };
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates a visual from screencaptures.
        /// </summary>
        /// <param name="sourceFile">Source file.</param>
        /// <param name="timeSpan">Time span where the capture has to be done.</param>
        /// <param name="visualSize">Reference to export dimensions of the visual.</param>
        /// <returns>Visual of the file.</returns>
        private Visual CreateVideoVisual(string sourceFile, TimeSpan timeSpan, out IntSize visualSize)
        {
            try {
                Uri sourceUri = new Uri(sourceFile);
                var mutexLock = new Mutex(false, sourceUri.GetHashCode().ToString());
                mutexLock.WaitOne();

                MediaPlayer mediaPayer = new MediaPlayer { Volume = 0, ScrubbingEnabled = true };
                mediaPayer.Open(sourceUri);

                mediaPayer.Pause();
                mediaPayer.Position = timeSpan;
                Thread.Sleep(1000);

                visualSize.Width = mediaPayer.NaturalVideoWidth;
                visualSize.Height = mediaPayer.NaturalVideoHeight;

                DrawingVisual drawingVisual = new DrawingVisual();
                using (DrawingContext drawingContext = drawingVisual.RenderOpen()) {
                    drawingContext.DrawVideo(mediaPayer, new Rect(0, 0, visualSize.Width, visualSize.Height));
                }
                mediaPayer.Close();
                mutexLock.ReleaseMutex();
                return drawingVisual;
            } catch {
                throw new Exception();
            }
        }
Ejemplo n.º 19
0
    public void CloseMediaPlayer(MediaPlayer player, bool synchronous = false) {
      Action closeAction = () => {
        player.Close();
        this.m_registeredPlayers.Remove(player);
      };

      if (synchronous) {
        Invoke(closeAction);
      } else {
        BeginInvoke(closeAction);
      }
    }
        /// <summary>
        /// Updates the media source on the player. This is called internally when a new playlist item is selected.
        /// </summary>
        /// <param name="mediaPlayer">The MediaPlayer to load the media source (playlist item) into.</param>
        /// <param name="oldMediaSource">The old media source (this is usually a PlaylistItem object).</param>
        /// <param name="newMediaSource">The new media source (this is usually a PlaylistItem object).</param>
        public static void UpdateMediaSource(MediaPlayer mediaPlayer, IMediaSource oldMediaSource, IMediaSource newMediaSource)
        {
            if (oldMediaSource != null)
            {
#if SILVERLIGHT
                mediaPlayer.LicenseAcquirer = new LicenseAcquirer();
#else
                mediaPlayer.ProtectionManager = null;
                mediaPlayer.Stereo3DVideoPackingMode = Stereo3DVideoPackingMode.None;
                mediaPlayer.Stereo3DVideoRenderMode = Stereo3DVideoRenderMode.Mono;
#endif
                mediaPlayer.VisualMarkers.Clear();
                mediaPlayer.AvailableAudioStreams.Clear();
                mediaPlayer.AvailableCaptions.Clear();
                mediaPlayer.PosterSource = null;
                mediaPlayer.Close();
            }

            foreach (var plugin in mediaPlayer.Plugins)
            {
                plugin.Update(newMediaSource);
            }

            if (newMediaSource != null)
            {
                var playlistItem = newMediaSource as PlaylistItem;

#if SILVERLIGHT
                mediaPlayer.LicenseAcquirer = newMediaSource.LicenseAcquirer ?? new LicenseAcquirer();
#else
                mediaPlayer.ProtectionManager = newMediaSource.ProtectionManager;
                mediaPlayer.Stereo3DVideoPackingMode = newMediaSource.Stereo3DVideoPackingMode;
                mediaPlayer.Stereo3DVideoRenderMode = newMediaSource.Stereo3DVideoRenderMode;
#endif
                mediaPlayer.PosterSource = newMediaSource.PosterSource;
                mediaPlayer.AutoLoad = newMediaSource.AutoLoad;
                mediaPlayer.AutoPlay = newMediaSource.AutoPlay;
                mediaPlayer.StartupPosition = newMediaSource.StartupPosition;
                mediaPlayer.VisualMarkers.Clear();
                foreach (var marker in newMediaSource.VisualMarkers)
                {
                    mediaPlayer.VisualMarkers.Add(marker);
                }
                mediaPlayer.AvailableAudioStreams.Clear();
                foreach (var audioStream in newMediaSource.AvailableAudioStreams)
                {
                    mediaPlayer.AvailableAudioStreams.Add(audioStream);
                }

                mediaPlayer.SelectedCaption = null;
                mediaPlayer.AvailableCaptions.Clear();
                foreach (var caption in newMediaSource.AvailableCaptions)
                {
                    mediaPlayer.AvailableCaptions.Add(caption);
                }

                if (newMediaSource.Source != null)
                {
                    mediaPlayer.Source = newMediaSource.Source;
                }
#if !SILVERLIGHT
                else if (playlistItem != null && playlistItem.SourceStream != null)
                {
                    mediaPlayer.SetSource(playlistItem.SourceStream, playlistItem.MimeType);
                }
#if !WINDOWS80
                else if (playlistItem != null && playlistItem.MediaStreamSource != null)
                {
                    mediaPlayer.SetMediaStreamSource(playlistItem.MediaStreamSource);
                }
#endif
#else
                else if (playlistItem != null && playlistItem.SourceStream != null)
                {
                    mediaPlayer.SetSource(playlistItem.SourceStream);
                }
                else if (playlistItem != null && playlistItem.MediaStreamSource != null)
                {
                    mediaPlayer.SetSource(playlistItem.MediaStreamSource);
                }
#endif
                else
                {
                    mediaPlayer.Source = null;
                }
            }
        }
Ejemplo n.º 21
0
        public void OnHostEvent(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState is Exception)
            {
                Exception ex = e.UserState as Exception;
                PopupString(ex.ToString() + "\r\n" + ex.StackTrace.ToString());
            }
            if (e.UserState is string)
            {
                /*
                 * string line = (string)e.UserState;
                 *
                 * textHistory.AppendText(line + "\r\n");
                 * textHistory.ScrollToEnd();
                 */
            }
            else if (e.UserState is EvalBundle)
            {
                EvalBundle b = (EvalBundle)e.UserState;
                ProcessEvals(b);
            }
            else if (e.UserState is DictBundle)
            {
                DictBundle b = (DictBundle)e.UserState;

                if (b.path == "download-result")
                {
                    OfferDownloads(b);
                    if (accessLibraryDlg != null)
                    {
                        accessLibraryDlg.Consider(b);
                    }
                }
                else
                {
                    if (b.path == "_gameaid/_filenames")
                    {
                        filenameDict = b.dict;
                    }

                    partyInfo1.Consider(b);
                    partyInfo2.Consider(b);
                    vs1.Consider(b);
                    readyRolls.Consider(b);

                    if (openSaveRollsDlg != null)
                    {
                        openSaveRollsDlg.Consider(b);
                    }

                    map1.Consider(b);
                    map2.Consider(b);

                    foreach (var sq in Squad.Children)
                    {
                        var sheet = sq as VirtualSheet;
                        if (sheet != null)
                        {
                            sheet.Consider(b);
                        }
                    }
                }
            }
            else if (e.UserState is DownloadFile)
            {
                DownloadFile file = e.UserState as DownloadFile;

                // Configure open file dialog box
                var dlg = new System.Windows.Forms.SaveFileDialog();
                dlg.Title           = "Save Download";
                dlg.FileName        = file.name;
                dlg.DefaultExt      = ".xlsx";                           // Default file extension
                dlg.Filter          = "Character Sheets (.xlsx)|*.xlsx"; // Filter files by extension
                dlg.OverwritePrompt = true;
                dlg.CheckPathExists = true;

                // Show open file dialog box
                System.Windows.Forms.DialogResult result = dlg.ShowDialog();

                // Process open file dialog box results
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        System.IO.File.WriteAllBytes(dlg.FileName, file.bytes);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message);
                        return;
                    }
                }
            }
            else if (e.UserState is AudioReport)
            {
                AudioReport audio = e.UserState as AudioReport;

                string url = "";

                switch (audio.desc)
                {
                case "speak":
                    if (reader == null)
                    {
                        try
                        {
                            // tolerate reader acquisition failure more gracefully

                            reader = new SpeechSynthesizer();

                            // var l = new List<VoiceInfo>();
                            //
                            // foreach (InstalledVoice voice in reader.GetInstalledVoices())
                            // {
                            //     VoiceInfo info = voice.VoiceInfo;
                            //     string AudioFormats = "";
                            //     foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
                            //     {
                            //         AudioFormats += String.Format("{0}\n",
                            //         fmt.EncodingFormat.ToString());
                            //     }
                            //
                            //     l.Add(info);
                            //
                            // }

                            reader.SelectVoice("Microsoft Zira Desktop");
                        }
                        catch
                        {
                        }
                    }

                    if (reader != null)
                    {
                        reader.SpeakAsync(audio.text);
                    }
                    break;

                case "ownage":
                    switch (audio.killcount)
                    {
                    case 1:
                        url = "http://myserver.com/uploads/killshot/1.mp3";
                        break;

                    case 2:
                        url = "http://myserver.com/uploads/killshot/4.mp3";
                        break;

                    case 3:
                        url = "http://myserver.com/uploads/killshot/6.mp3";
                        break;

                    case 4:
                        url = "http://myserver.com/uploads/killshot/7.mp3";
                        break;

                    case 5:
                        url = "http://myserver.com/uploads/killshot/10.mp3";
                        break;

                    case 6:
                        url = "http://myserver.com/uploads/killshot/9.mp3";
                        break;

                    case 7:
                    default:
                        url = "http://myserver.com/uploads/killshot/14.mp3";
                        break;
                    }
                    break;

                case "fumble":
                    url = "http://myserver.com/uploads/killshot/0.mp3";
                    break;

                default:
                    url = "http://myserver.com/uploads/misc/" + audio.desc;
                    break;
                }

                if (url != "")
                {
                    var player = new System.Windows.Media.MediaPlayer();
                    player.Open(new Uri(url));
                    player.MediaOpened += new EventHandler((object s, EventArgs a) => { player.Play(); });
                    player.MediaEnded  += new EventHandler((object s, EventArgs a) => { player.Close(); });
                }
            }
            else if (e.UserState is HoursReport)
            {
                HoursReport h = e.UserState as HoursReport;
                vs1.SetRemainingHours(h.hours);
            }
        }
Ejemplo n.º 22
0
        public async override Task<BitmapSource> LoadBitmapAsync(string imageFolderPath, Nullable<int> desiredWidth)
        {
            string path = this.GetFilePath(imageFolderPath);
            if (!File.Exists(path))
            {
                return Constant.Images.FileNoLongerAvailable.Value;
            }

            BitmapSource firstFrame = await Task.Run(() =>
            {
                for (int renderAttempt = 0; renderAttempt < Constant.ThrottleValues.MaximumRenderAttempts; ++renderAttempt)
                {
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.Volume = 0.0;
                    try
                    {
                        mediaPlayer.Open(new Uri(path));
                        mediaPlayer.Play();

                        // MediaPlayer is not actually synchronous despite exposing synchronous APIs, so wait for it get the video loaded.  Otherwise
                        // the width and height properties are zero and only black pixels are drawn.  The properties will populate with just a call to
                        // Open() call but without also Play() only black is rendered.  It would be preferable to hook, say, mediaPlayer.MediaOpened
                        // for this purpose but the event doesn't seem to be fired.
                        while ((mediaPlayer.NaturalVideoWidth < 1) || (mediaPlayer.NaturalVideoHeight < 1))
                        {
                            // back off briefly to let MediaPlayer do its loading, which typically takes perhaps 75ms
                            // a brief Sleep() is used rather than Yield() to reduce overhead as 500k to 1M+ yields typically occur
                            Thread.Sleep(Constant.ThrottleValues.PollIntervalForVideoLoad);
                        }

                        // sleep one more time as MediaPlayer has a tendency to still return black frames for a moment after the width and height have populated
                        Thread.Sleep(Constant.ThrottleValues.PollIntervalForVideoLoad);

                        int pixelWidth = mediaPlayer.NaturalVideoWidth;
                        int pixelHeight = mediaPlayer.NaturalVideoHeight;
                        if (desiredWidth.HasValue)
                        {
                            double scaling = (double)desiredWidth.Value / (double)pixelWidth;
                            pixelWidth = (int)(scaling * pixelWidth);
                            pixelHeight = (int)(scaling * pixelHeight);
                        }

                        // set up to render frame from the video
                        mediaPlayer.Pause();
                        mediaPlayer.Position = TimeSpan.FromMilliseconds(1.0);

                        // render and check for black frame
                        // it's assumed the camera doesn't yield all black frames
                        DrawingVisual drawingVisual = new DrawingVisual();
                        for (int blackFrameAttempt = 1; blackFrameAttempt <= Constant.ThrottleValues.MaximumBlackFrameAttempts; ++blackFrameAttempt)
                        {
                            // try render
                            // creating the DrawingContext insie the loop but persisting the DrawingVisual seems to produce the highest success rate.
                            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                            {
                                drawingContext.DrawVideo(mediaPlayer, new Rect(0, 0, pixelWidth, pixelHeight));
                                RenderTargetBitmap renderBitmap = new RenderTargetBitmap(pixelWidth, pixelHeight, 96, 96, PixelFormats.Default);
                                renderBitmap.Render(drawingVisual);
                                renderBitmap.Freeze();

                                // check if render succeeded
                                // hopefully it did and most of the overhead here is WriteableBitmap conversion though, at 2-3ms for a 1280x720 frame, black 
                                // checking is not an especially expensive operation relative to the O(175ms) cost of this function
                                WriteableBitmap writeableBitmap = renderBitmap.AsWriteable();
                                if (writeableBitmap.IsBlack() == false)
                                {
                                    // Debug.Print("Video frame succeeded: render attempt {0}, black frame attempt {1}.", renderAttempt, blackFrameAttempt);
                                    // If the media player is closed before Render() only black is rendered.
                                    // If the WriteableBitmap isn't cast the compiler can't figure out the delegate's return type.
                                    mediaPlayer.Close();
                                    return (BitmapSource)writeableBitmap;
                                }
                            }

                            // black frame was rendered; apply linear backoff and try again
                            Thread.Sleep(TimeSpan.FromMilliseconds(Constant.ThrottleValues.RenderingBackoffTime.TotalMilliseconds * renderAttempt));
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.Fail(String.Format("Loading of {0} failed.", this.FileName), exception.ToString());
                        return Constant.Images.CorruptFile.Value;
                    }

                    mediaPlayer.Close();
                }

                throw new ApplicationException(String.Format("Limit of {0} render attempts reached.", Constant.ThrottleValues.MaximumRenderAttempts));
            });

            return firstFrame;
        }
Ejemplo n.º 23
0
 private void playSong()
 {
     mp = new MediaPlayer();
     this.read = true;
     var source = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).ToString()).ToString() + "/Assets/" + level.musique;
     mp.MediaEnded += this.close;
     mp.Open(new Uri(source));
     while (read)
     {
         mp.Play();
     }
     mp.Close();
 }