WPF 4 Media Player (MediaElement)

Source: Internet
Author: User

In WPF, you can use MediaElement to add media playback controls for applications to play audio and video. Because MediaElement is a UIElement, it also supports mouse and keyboard operations. This article uses the MediaElement class and Windows API Code Pack to create a simple video player for some basic functions.

Interface framework

Put a MediaElement control in XAML (supports video playback ), five Button controls (for "Open video Document", "Play/pause", "stop", "Fast forward", and "Fast Forward"), and one Slider control (for controlling the volume ).

<StackPanel HorizontalAlignment="Center" Margin="20">    <Border BorderThickness="3" Background="Black">        <Border.BorderBrush>            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">                <GradientStop Offset="0" Color="White"/>                <GradientStop Offset="0.5" Color="Gold"/>            </LinearGradientBrush>        </Border.BorderBrush>        <MediaElement Height="300" Width="450" Name="mediaElement" 
Volume="0.5" LoadedBehavior="Manual"
MouseLeftButtonUp="mediaElement_MouseLeftButtonUp"/> </Border> <StackPanel Orientation="Horizontal" Height="40" HorizontalAlignment="Center"> <Button x:Name="openBtn" Content="Open File" Style="{StaticResource btnStyle}" Click="openBtn_Click"/> <Button x:Name="playBtn" Content="Play" Style="{StaticResource btnStyle}" Click="playBtn_Click"/> <Button x:Name="stopBtn" Content="Stop" Style="{StaticResource btnStyle}" Click="stopBtn_Click"/> <Button x:Name="backBtn" Content="Back" Style="{StaticResource btnStyle}" Click="backBtn_Click"/> <Button x:Name="forwardBtn" Content="Forward" Style="{StaticResource btnStyle}" Click="forwardBtn_Click"/> </StackPanel> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="5"> <TextBlock Text="Volume" Foreground="Gold"/> <Slider x:Name="volumeSlider" Minimum="0" Maximum="1" Value="0.5" Width="200"/> </StackPanel></StackPanel>

Note:LoadedBehaviorSetManualIn this way, you can manually control the video playback status.

Interface Style

Some simple styles have been set for some controls in the code above. The Button control uses static resource btnStyle for complex style settings. First, the default style of the Button is modified, and the font color changes when you move the cursor over the Button.

<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="FontStyle" Value="Italic"/>        <Setter Property="Margin" Value="5"/>        <Setter Property="Width" Value="60"/>        <Setter Property="Foreground" Value="Gold"/>        <Style.Triggers>            <Trigger Property="Button.IsMouseOver" Value="True">                <Setter Property="Foreground" Value="Black"/>            </Trigger>        </Style.Triggers>    </Style></Window.Resources>

Browse video files

Introduce the Windows API Code Pack in the video file browsing section, use the KnownFolders class to direct the file browsing window to the Sample Videos directory of the media library, and add the WMV and AVI file filters.

private void openBtn_Click(object sender, RoutedEventArgs e){    ShellContainer selectedFolder = null;    selectedFolder = KnownFolders.SampleVideos as ShellContainer;    CommonOpenFileDialog cfd = new CommonOpenFileDialog();    cfd.InitialDirectoryShellContainer = selectedFolder;    cfd.EnsureReadOnly = true;    cfd.Filters.Add(new CommonFileDialogFilter("WMV Files", "*.wmv"));    cfd.Filters.Add(new CommonFileDialogFilter("AVI Files", "*.avi"));
cfd.Filters.Add(new CommonFileDialogFilter("MP3 Files", "*.mp3")); if (cfd.ShowDialog() == CommonFileDialogResult.OK) { mediaElement.Source = new Uri(cfd.FileName, UriKind.Relative); playBtn.IsEnabled = true; }}

Play/pause

During video playback, you can click Play/Pause or MediaElement to Play or Pause the video.

private void PlayerPause(){    SetPlayer(true);    if (playBtn.Content.ToString() == "Play")    {        mediaElement.Play();        playBtn.Content = "Pause";        mediaElement.ToolTip = "Click to Pause";    }    else    {        mediaElement.Pause();        playBtn.Content = "Play";        mediaElement.ToolTip = "Click to Play";    }}private void playBtn_Click(object sender, RoutedEventArgs e){    PlayerPause();}private void mediaElement_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){    PlayerPause();}

Fast Return/Fast Forward

You can adjust the video progress by modifying the Position value of MediaElement. The interval is set through TimeSpan (the following code uses the interval of 10 seconds ).

private void backBtn_Click(object sender, RoutedEventArgs e){    mediaElement.Position = mediaElement.Position - TimeSpan.FromSeconds(10);}private void forwardBtn_Click(object sender, RoutedEventArgs e){    mediaElement.Position = mediaElement.Position + TimeSpan.FromSeconds(10);}

Volume Adjustment

In the volume adjustment section, you only need to set the SliderValueChange Value and MediaElementVolumeMake a simple Binding.

......<MediaElement Height="300" Width="450" Name="mediaElement" LoadedBehavior="Manual"
Volume="{Binding ElementName=volumeSlider, Path=Value}" MouseLeftButtonUp="mediaElement_MouseLeftButtonUp"/>......

Source program download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.