Part 20 - Playing Video and Audio in a MediaElement Control

Play Part 20 - Playing Video and Audio in a MediaElement Control
Sign in to queue

Description

Download the source code for this lesson at http://absolutebeginner.codeplex.com/

You may think it an odd transition from talking about MVVM and awaitable tasks to something rather fun and mundane like playing video and audio in your phone app, however this is the last lesson before we go off and build a full app based on the ideas we’ve learned thus far.  I won’t spoil the surprise by foreshadowing what it is we’ll be building, but it will involve playing video and the Hub App Template just to show how flexible the Hub App Template is with a little imagination.

To keep the example as simple as possible, I’m going to create a new Blank App Template project called “SoundAndVideo”.

I will illustrate some very simple scenarios in this lesson … just a bit more than we’ll need for our full featured app in the next lesson, but not enough to go off and create some great audio player app.  You’ll want to consult the documentation if you have a more advanced scenario.

I’ll begin by adding the XAML for my project:

    <StackPanel>
        <MediaElement x:Name="myMediaElement"
                      Height="10"
                      Width="10"
                      Source="/Assets/Duck.wav"
                      />
       
    </StackPanel>

Also, I’ll copy the Duck.wav file from the assets I’ve included with this series to the \Assets folder in my project by dragging-and-dropping from Windows Explorer to Visual Studio.

When I run the app, I immediately hear the Duck quacking.  Admittedly, the sound is briefly interrupted during playback, but I’ve marked that up to the fact that there’s a lot going on during the deployment from Visual Studio to the emulator.

What if I do not want the sound to play immediately, but only want it to play when I click a button?

        <MediaElement x:Name="myMediaElement"
                      Height="10"
                      Width="10"
                      Source="/Assets/Duck.wav"
                      AutoPlay="False"
                      />

        <Button x:Name="playSoundButton"
                Height="80"
                Width="200"
                Content="Play Sound"
                Click="playSoundButton_Click" />

I added the AutoPlay=”False” to stop the sound from playing automatically.  In the button’s click event:

private void playSoundButton_Click(object sender, RoutedEventArgs e)
{
  myMediaElement.Play();
}

What if I want to use this same MediaElement for multiple sounds or videos?  First, I would remove the Source and AutoPlay properties:

        <MediaElement x:Name="myMediaElement"
                      Height="10"
                      Width="10"
                      />

And I would set the Source property in code:

private void playSoundButton_Click(object sender, RoutedEventArgs e)
{
  myMediaElement.Source = new Uri("ms-appx:///Assets/Duck.wav", UriKind.RelativeOrAbsolute);
  myMediaElement.Play();
}

The ms-appx:/// means “look for this in the current app package once it is deployed to the Phone.

What if I want to use the same MediaElement to play both an audio file AND a video file?  I’ll make the size of the MediaElement larger to accommodate the video:

        <MediaElement x:Name="myMediaElement"
                      Margin="0,40,0,40"
                      Height="400"
                      Width="240" />

I’ll add a button:

        <Button x:Name="playVideoButton"
                Height="80"
                Width="200"
                Content="Play Video"
                Click="playVideoButton_Click"/>

I’ll copy the video named coffee.mp4 file from the assets I’ve included with this series to the \Assets folder in my project by dragging-and-dropping from Windows Explorer to Visual Studio.

And I’ll handle the button’s click event:

private void playVideoButton_Click(object sender, RoutedEventArgs e)
{
  myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);
  myMediaElement.Play();
}

What if I want to pause the video during playback?  I would need to keep track of the current state of the MediaElement.  I suppose there are many ways to do that, but I can imagine several states: Playing, Paused, Stopped.  So, I’ll add a new class file to create an enum called MediaState:

    public enum MediaState
    {
        Stopped,
        Playing,
        Paused
    }

Then I’ll use that to perform the following logic:

        private MediaState state = MediaState.Stopped;

        private void playVideoButton_Click(object sender, RoutedEventArgs e)
        {
            if (state==MediaState.Stopped)
            {
                myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);
                state = MediaState.Playing;
                myMediaElement.Play();
            }
            else if (state==MediaState.Playing)
            {
                state = MediaState.Paused;
                myMediaElement.Pause();
            }
            else if (state==MediaState.Paused)
            {
                state = MediaState.Playing;
                myMediaElement.Play();
            }
        }

I’ll also modify the MediaElement to handle the MediaEnded event in order to set the MediaState back to Stopped.

<MediaElement x:Name="myMediaElement"
    Margin="0,40,0,40"
    Height="400"
    Width="240"
    MediaEnded="myMediaElement_MediaEnded" />

Finally, I’ll handle the MediaEnded event:

private void myMediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
  state=MediaState.Stopped;
}

As I said at the outset, there are more features of the MediaElement than we’ll discuss.  However, this will at least get you started thinking about what’s possible.  In the next lesson, we’ll put many of these ideas together to create an entire app.

Embed

Download

Download this episode

The Discussion

  • User profile image
    LordSpaz​Monkey

    Hi Bob,

    First off i'd just like to say I love the videos and I am looking at signing up to LearnVisualStudio.Net to learn more, if my University Lecturers were as good as you I might have understood more than just the absolute basics.

    I'm trying to create a sort of amalgamation between this SoundBoard App and the Hub App template so that when I click on any of the item tiles instead of taking me to an item page it plays a sound in myMediaElement based on the UniqueId, kind of like what you have done in the I Love Cupcakes app a couple of lessons on from this.

    This is what I have so far in my HubPage.xaml.cs.

    private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
            {
                var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;

                           
                var uri = "ms-appx:///Assets/" + itemId + ".wav";
                myMediaElement.Source = new Uri(uri, UriKind.Absolute);
                myMediaElement.Play();
            }

     

    It runs fine but breaks when I try to click the button and I'm not sure where I'm going wrong. Any chance you could help me with this?

     

    Thanks,

     

  • User profile image
    ahmed

    how I embed a link or a video URL in my media element, is related with api, data parasing or data binding....

  • User profile image
    Cyberlacs

    How to insert a list of videos to play

    List<string> videos10 = new List<string>();
    videos10.Add("Call Farma");
    videos10.Add("Dia Mundial");
    videos10.Add("Dolex Nueva");
    videos10.Add("Mori Farma");

    foreach (var item in videos10)
    {

    try
    {
    Uri pathUri = new Uri("ms-appx:///Videos/" + item + ".mp4");
    mediaPlayer.Source = pathUri;
    }
    catch (Exception ex)
    {
    throw;
    }
    }

Add Your 2 Cents