For the Interface paste the following code in the MainPage.XAML

  1. <StackPanel>
  2. <MediaElement x:Name="myMediaElement"
  3. Height="400"
  4. Width="240"
  5. Margin="0,40,0,40"
  6. MediaEnded="myMediaElement_MediaEnded"
  7. />
  8. <Button x:Name="playSoundButton"
  9. Height="80"
  10. Width="390"
  11. Content="Play Sound"
  12. Click="playSoundButton_Click"/>
  13. <Button x:Name="playVideoButton"
  14. Height="80"
  15. Content="Play video"
  16. Click="playVideoButton_Click" HorizontalAlignment="Stretch" Margin="0,0,10,0"
  17. />
  18. </StackPanel>

This Code Will Create Layout Like in the below Image:

In the MainPage.XAML.CS create an enum for the Media Element like this:

  1. public enum MediaState
  2. {
  3. Stopped,
  4. Playing,
  5. Paused
  6. }


The Default State of the Media would be stopped:

  1. private MediaState state = MediaState.Stopped;

We will use this enum to find out the media state of the element.

Paste the following code in the playVideoButton_Click event

  1. if(state == MediaState.Stopped)
  2. {
  3. myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);
  4. playVideoButton.Content = "Playing";
  5. playVideoButton.Background = new SolidColorBrush(Colors.Green);
  6. state = MediaState.Playing;
  7. myMediaElement.Play();
  8. }
  9. else if(state == MediaState.Playing)
  10. {
  11. playVideoButton.Content = "Paused";
  12. playVideoButton.Background = new SolidColorBrush(Colors.Yellow);
  13. state = MediaState.Paused;
  14. myMediaElement.Pause();
  15. }
  16. else if(state == MediaState.Paused)
  17. {
  18. playVideoButton.Content = "Playing";
  19. playVideoButton.Background = new SolidColorBrush(Colors.Green);
  20. state = MediaState.Playing;
  21. myMediaElement.Play();
  22. }

In the playSoundButton_Click event Paste the following code:

  1. if ( state == MediaState.Playing || state == MediaState.Paused)
  2. {
  3. playVideoButton.Content = "Stopped";
  4. playVideoButton.Background = new SolidColorBrush();
  5. }
  6. myMediaElement.Source = new Uri("ms-appx:///Assets/Duck.wav", UriKind.RelativeOrAbsolute );
  7. myMediaElement.Play();

Paste the below code to set out the media state of the element after the media ended:

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