public void Pause()
        {
            _player.Pause();
            _positionTimer.Stop();

            IsPlaying = false;
            IsPaused  = true;
            IsStopped = false;
        }
Exemple #2
0
 /// <summary>
 /// 播放按钮被按下
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (!isPlaying)
     {
         isPlaying         = true;
         Buttonplay.Source = pauseBitmapImage;
         media             = new MediaPlayer();//播放类
         Thread t1 = new Thread(new ThreadStart(InitSong));
         t1.Start();
     }
     else
     {
         media.Pause();
         isPlaying         = false;
         Buttonplay.Source = playingImage;
     }
 }
        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();
        }
Exemple #4
0
 public void Pause()
 {
     _internalPlayer.Pause();
 }
 public void Pause()
 {
     _player.Pause();
     sync.Stop();
 }
Exemple #6
0
 /// <summary>
 /// 一時停止
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void PauseButton_Click(object sender, RoutedEventArgs e)
 {
     player.Pause();
     isPaused = true;
     PortUtil.Instance.SendStop();
 }
        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;
        }
Exemple #8
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;
        }
Exemple #9
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();
            }
        }
Exemple #10
0
 public void Pause()
 {
     player.Pause();
 }
        public static ImageSource GetThumbnailFromVideo(string filename, TimeSpan interval, int height)
        {
            //configurations.the_flag++;
            MediaPlayer _mediaPlayer = new MediaPlayer();
            _mediaPlayer.MediaOpened += new EventHandler(configurations._mediaPlayer_MediaOpened);
            _mediaPlayer.BufferingEnded += new EventHandler(configurations._mediaPlayer_MediaOpened);
            _mediaPlayer.ScrubbingEnabled = true;
            _mediaPlayer.Open(new Uri(configurations.GetAbsoluteContributionPath() + filename));
            _mediaPlayer.Pause();
            //_mediaPlayer.Position = interval;
            System.Threading.Thread.Sleep(5 * 1000);

            //while (the_flag != 0) { System.Threading.Thread.Sleep(1000); }
            _mediaPlayer.Position = interval;
            ImageSource src = new BitmapImage(new Uri(configurations.GetAbsoluteImagePath() + video_image_pic));
            src.Freeze();
            //uint[] framePixels = new uint[width * height];
            // Render the current frame into a bitmap
            var drawingVisual = new DrawingVisual();
            try
            {
                int width = height;
                if (_mediaPlayer.NaturalVideoWidth * _mediaPlayer.NaturalVideoHeight != 0)
                    width = height * _mediaPlayer.NaturalVideoWidth / _mediaPlayer.NaturalVideoHeight;
                using (var drawingContext = drawingVisual.RenderOpen())
                {
                    drawingContext.DrawVideo(_mediaPlayer, new System.Windows.Rect(0, 0, width, height));
                    drawingContext.DrawImage(src, new System.Windows.Rect(0, 0, width, height));
                    //drawingContext.DrawVideo(_mediaPlayer, new System.Windows.Rect(0, 0, height, height));
                    //drawingContext.DrawImage(src, new System.Windows.Rect(0, 0, height, height));
                }
                var renderTargetBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
                //var renderTargetBitmap = new RenderTargetBitmap(height, height, 96, 96, PixelFormats.Default);
                renderTargetBitmap.Render(drawingVisual);
                return (ImageSource)renderTargetBitmap;
            }
            catch (Exception exc) { log.WriteErrorLog(exc); return null; }
        }