For the Interface paste the following code in the MainPage.XAML
- <StackPanel>
- <MediaElement x:Name="myMediaElement"
- Height="400"
- Width="240"
- Margin="0,40,0,40"
- MediaEnded="myMediaElement_MediaEnded"
-
- />
- <Button x:Name="playSoundButton"
- Height="80"
- Width="390"
- Content="Play Sound"
- Click="playSoundButton_Click"/>
- <Button x:Name="playVideoButton"
- Height="80"
- Content="Play video"
- Click="playVideoButton_Click" HorizontalAlignment="Stretch" Margin="0,0,10,0"
- />
-
- </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:
- public enum MediaState
- {
- Stopped,
- Playing,
- Paused
- }
The Default State of the Media would be stopped:
- 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
- if(state == MediaState.Stopped)
- {
-
-
- myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);
- playVideoButton.Content = "Playing";
- playVideoButton.Background = new SolidColorBrush(Colors.Green);
- state = MediaState.Playing;
- myMediaElement.Play();
-
-
-
- }
- else if(state == MediaState.Playing)
- {
- playVideoButton.Content = "Paused";
- playVideoButton.Background = new SolidColorBrush(Colors.Yellow);
-
-
- state = MediaState.Paused;
- myMediaElement.Pause();
-
-
- }
- else if(state == MediaState.Paused)
- {
- playVideoButton.Content = "Playing";
- playVideoButton.Background = new SolidColorBrush(Colors.Green);
- state = MediaState.Playing;
- myMediaElement.Play();
-
- }
In the playSoundButton_Click event Paste the following code:
- if ( state == MediaState.Playing || state == MediaState.Paused)
- {
- playVideoButton.Content = "Stopped";
- playVideoButton.Background = new SolidColorBrush();
- }
-
-
- myMediaElement.Source = new Uri("ms-appx:///Assets/Duck.wav", UriKind.RelativeOrAbsolute );
- myMediaElement.Play();
Paste the below code to set out the media state of the element after the media ended:
- private void myMediaElement_MediaEnded(object sender, RoutedEventArgs e)
- {
- state = MediaState.Stopped;
-
- }