- Select new -> project
- Select your preferred language
- Select a WPF application
- Name the project
- Now name of project is "WpfMediaElement"
Step 2 : Open the Toolbox of WPF application.
- Drag & Drop MediaElement control on design view.
- Add a vedio file with (.wmv) extension in project.
- put name of the vedio file in source property of MediaElement.
Step 3 : Set some formatting on the MediaElement control tag in the XAML page.
Code
<MediaElement Name="myMedia" Source="Wildlife.wmv"
LoadedBehavior="Manual" Width="320" Height="240" />
Step 4 : Add three button control for Play, Mute and Pause actions in XAML page.
Code
<Button Content="Play" Margin="0,0,10,0"
Padding="5" Click="mediaPlay" />
<Button Content="Pause" Margin="0,0,10,0"
Padding="5" Click="mediaPause" />
<Button x:Name="muteButt" Content="Mute"
Padding="5" Click="mediaMute" />
Step 5 : Now, the final source code of the XAML page is given below:
Code
<Window x:Class="WpfMediaElement.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<MediaElement Name="myMedia" Source="Wildlife.wmv"
LoadedBehavior="Manual" Width="320" Height="240" />
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<Button Content="Play" Margin="0,0,10,0"
Padding="5" Click="mediaPlay" />
<Button Content="Pause" Margin="0,0,10,0"
Padding="5" Click="mediaPause" />
<Button x:Name="muteButt" Content="Mute"
Padding="5" Click="mediaMute" />
</StackPanel>
</StackPanel>
</Grid>
</Window>
Step 6 : Now, we will go for code behind file MainWindow.xaml.cs file where we will create logic for the Click events for the Play, Pause and Mute buttons.
Code
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;
namespace WpfMediaElement
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeComponent();
myMedia.Volume = 100;
myMedia.Play();
}
void mediaPlay(Object sender, EventArgs e)
{
myMedia.Play();
}
void mediaPause(Object sender, EventArgs e)
{
myMedia.Pause();
}
void mediaMute(Object sender, EventArgs e)
{
if (myMedia.Volume == 100)
{
myMedia.Volume = 0;
muteButt.Content = "Listen";
}
else
{
myMedia.Volume = 100;
muteButt.Content = "Mute";
}
}
}
}
Output
Resources