This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Media Controls - MediaElement - Playing Media

The eighty-fifth part of the Windows Presentation Foundation Fundamentals tutorial begins to look at the MediaElement control. This control allows the playing of a wide range of media, including audio and video.


The MediaElement class provides the second of the WPF media controls that we will consider in this tutorial. MediaElement allows you to play audio or present video within a rectangular area of the screen. You can play the media automatically or control it using various methods. The control includes most of the features that you might expect of a music or video player, such as the ability to play, pause and stop the media, members for adjusting the volume and audio balance and a property that allows you to speed up or slow down playback.

MediaElement is a complex class with lots of methods, properties and events. We'll look at the main members in this and subsequent articles. In this instalment we'll use the basic features to create a simple media player.

To begin, create a new WPF application project in Visual Studio named, "MediaElementDemo". Once the solution is ready, replace the XAML in the main window with the code below:

<Window x:Class="MediaElementDemo.MainWindow"
        Title="MediaElement Demo"
            <ColumnDefinition Width="80"/>
            <RowDefinition Height="22"/>

        <Border BorderBrush="White" BorderThickness="1">
            <MediaElement Name="Media" Margin="2"/>

        <TextBlock Name="MediaName" Grid.Row="1" Foreground="White">No Media</TextBlock>

        <StackPanel Grid.Column="1">
            <ToggleButton Margin="0 5 0 0">Mute</ToggleButton>

            <TextBlock FontSize="10">Volume</TextBlock>
            <Slider Name="VolumeSlider" Value="0.75" Maximum="1"/>

            <TextBlock FontSize="10">Balance</TextBlock>
            <Slider Name="BalanceSlider" Value="0" Minimum="-1" Maximum="1"/>

            <TextBlock FontSize="10">Speed</TextBlock>
            <Slider Name="SpeedSlider"
                    Value="1" Minimum="0" Maximum="4"
                    0, 0.25, 0.5, 1, 2, 4

        <Button Grid.Row="1" Grid.Column="1">Load</Button>

The XAML produces a window containing a MediaElement control and some buttons and sliders that we will use to control playback. So far the player includes no functionality. However, you can run the program to see the layout.

WPF MediaElement demonstration window

5 August 2014