WPF媒体播放器(MediaElement)打开指定的视频、播放、暂停、快进、快退、截图

时间:2023-01-31 23:07:07

WPF媒体播放器(MediaElement)打开指定的视频、播放、暂停、快进、快退、截图

XAML

<Window x:Class="MediaSampleWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF100" Height="413" Width="632">
    <Window.Resources>
        <Style x:Key="btnStyle" TargetType="Button">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                        <GradientStop Offset="0" Color="White"/>
                        <GradientStop Offset="0.5" Color="#FF554D4A"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="Width" Value="60"/>
            <Setter Property="Foreground" Value="YellowGreen"/>
            <Style.Triggers>
                <Trigger Property="Button.IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Black"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid x:Name="LayoutRoot" Background="Black">
        <Grid.RowDefinitions>
            <RowDefinition Height="322*" />
            <RowDefinition Height="53*" />
        </Grid.RowDefinitions>
        <MediaElement x:Name="MediaEL" MediaOpened="MediaEL_MediaOpened" MediaEnded="MediaEL_MediaEnded"
                      LoadedBehavior="Manual" Margin="0,10"/>
        <StackPanel Orientation="Vertical" Margin="120,0" Grid.Row="1">
            <StackPanel x:Name="SPSeekBar" HorizontalAlignment="Stretch">
                <Slider x:Name="seekBar" Thumb.DragStarted="seekBar_DragStarted"
                        Thumb.DragCompleted="seekBar_DragCompleted" />
            </StackPanel>
            <Rectangle Height="5"/>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button x:Name="btnPlay" Content="播放" Click="btnPlay_Click" Style="{StaticResource btnStyle}"
                    Width="50" Height="25" Margin="5,0"/>
                <Button x:Name="btnStop" Content="停止" Click="btnStop_Click"  Style="{StaticResource btnStyle}"
                    Width="50" Height="25" Margin="5,0"/>
                <Button x:Name="btnMoveBackward" Content="后退" Click="btnMoveBackward_Click"  Style="{StaticResource btnStyle}"
                    Width="50" Height="25" Margin="5,0"/>
                <Button x:Name="btnMoveForward" Content="前进" Click="btnMoveForward_Click"  Style="{StaticResource btnStyle}"
                    Width="50" Height="25" Margin="5,0"/>
                <Button x:Name="btnOpen" Content="打开" Click="btnOpen_Click"  Style="{StaticResource btnStyle}"
                    Width="50" Height="25" Margin="5,0"/>
                <Button x:Name="btnScreenShot" Content="截屏" Click="btnScreenShot_Click" Width="50" Height="25" Margin="5,0" Style="{StaticResource btnStyle}" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

CS

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;

namespace MediaSampleWPF
{
    public partial class Window1 : Window
    {
        DispatcherTimer timer;

        #region Constructor
        public Window1()
        {
            InitializeComponent();
            IsPlaying(false);
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(10);
            timer.Tick += new EventHandler(timer_Tick);
        }
        #endregion

        #region IsPlaying(bool)
        private void IsPlaying(bool bValue)
        {
            btnStop.IsEnabled = bValue;
            btnMoveBackward.IsEnabled = bValue;
            btnMoveForward.IsEnabled = bValue;
            btnPlay.IsEnabled = bValue;
            btnScreenShot.IsEnabled = bValue;
            seekBar.IsEnabled = bValue;
        }
        #endregion

        #region Play and Pause
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            IsPlaying(true);
            if (btnPlay.Content.ToString() == "播放")
            {
                MediaEL.Play();
                btnPlay.Content = "暂停";
            }
            else
            {
                MediaEL.Pause();
                btnPlay.Content = "播放";
            }
        }
        #endregion

        #region Stop
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            MediaEL.Stop();
            btnPlay.Content = "播放";
            IsPlaying(false);
            btnPlay.IsEnabled = true;
        }
        #endregion

        #region Back and Forward
        private void btnMoveForward_Click(object sender, RoutedEventArgs e)
        {
            MediaEL.Position = MediaEL.Position + TimeSpan.FromSeconds(10);
        }

        private void btnMoveBackward_Click(object sender, RoutedEventArgs e)
        {
            MediaEL.Position = MediaEL.Position - TimeSpan.FromSeconds(10);
        }
        #endregion

        #region Open Media
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "Video Files (*.wmv)|*.wmv";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MediaEL.Source = new Uri(ofd.FileName);
                btnPlay.IsEnabled = true;
            }
        }
        #endregion

        #region Capture Screenshot
        private void btnScreenShot_Click(object sender, RoutedEventArgs e)
        {
            byte[] screenshot = MediaEL.GetScreenShot(1, 90);
            FileStream fileStream = new FileStream(@"Capture.jpg", FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);
            binaryWriter.Write(screenshot);
            binaryWriter.Close();
        }
        #endregion

        #region Seek Bar
        private void MediaEL_MediaOpened(object sender, RoutedEventArgs e)
        {
            if (MediaEL.NaturalDuration.HasTimeSpan)
            {
                TimeSpan ts = MediaEL.NaturalDuration.TimeSpan;
                seekBar.Maximum = ts.TotalSeconds;
                seekBar.SmallChange = 1;
                seekBar.LargeChange = Math.Min(10, ts.Seconds / 10);
            }
            timer.Start();
        }

        bool isDragging = false;

        void timer_Tick(object sender, EventArgs e)
        {
            if (!isDragging)
            {
                seekBar.Value = MediaEL.Position.TotalSeconds;
            }
        }

        private void seekBar_DragStarted(object sender, DragStartedEventArgs e)
        {
            isDragging = true;
        }

        private void seekBar_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            isDragging = false;
            MediaEL.Position = TimeSpan.FromSeconds(seekBar.Value);
        }
        #endregion

        #region MediaEnd
        private void MediaEL_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaEL.Stop();
            btnPlay.Content = "播放";
        }
        #endregion
    }

    #region Extension Methods
    public static class ScreenShot
    {
        public static byte[] GetScreenShot(this UIElement source, double scale, int quality)
        {
            double actualHeight = source.RenderSize.Height;
            double actualWidth = source.RenderSize.Width;
            double renderHeight = actualHeight * scale;
            double renderWidth = actualWidth * scale;

            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth,
                (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
            VisualBrush sourceBrush = new VisualBrush(source);

            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            using (drawingContext)
            {
                drawingContext.PushTransform(new ScaleTransform(scale, scale));
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0),
                    new Point(actualWidth, actualHeight)));
            }
            renderTarget.Render(drawingVisual);

            JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
            jpgEncoder.QualityLevel = quality;
            jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

            Byte[] imageArray;

            using (MemoryStream outputStream = new MemoryStream())
            {
                jpgEncoder.Save(outputStream);
                imageArray = outputStream.ToArray();
            }
            return imageArray;
        }
    }
    #endregion
}

 

你可以到http://www.wpf100.com/html/5/2012-03/article-167.html下载源码