Search code examples
c#xamlwindows-phone-8mediaelement

How to check if MediaElement has stopped?


I need to check, if MediaElement stopped at the moment or played. This is my code:

private void PlayAudioClick(object sender, RoutedEventArgs e)
{
    AudioPlayer.Play();
    StopAudio.Visibility = Visibility.Visible;
    PlayAudio.Visibility = Visibility.Collapsed;
    if (AudioPlayer.Stoped == true)
    {
        PlayAudio.Visibility = Visibility.Visible;
        StopAudio.Visibility = Visibility.Collapsed;
    }
}

I am looking for something like this pseudocode: if (AudioPlayer.Stoped == true) {//do something}.


Solution

  • You can use MediaElement 's MediaEnded event to check when the media has ended playing..

    In XAML

    <MediaElement Name="media" MediaEnded="media_MediaEnded"  />
    

    In C# code

    media.MediaEnded += media_MediaEnded;
    

    The event handler would look like..

    private void media_MediaEnded(object sender, RoutedEventArgs e)
    {
        // Do your stuff       
    }
    

    Also to detect the Current media state you have a enum Called MediaElementState you can get this by calling the CurrentState property in the MediaElement When put in a switch you can see all the states.

    The MediaElement also has a CurrentStateChanged event also.. This event fires when the state of the MediaElement get changed and you can use this in combination with CurrentState property to check what state the media is in.

    In XAML

    CurrentStateChanged="media_CurrentStateChanged"
    

    or in C#

    media.CurrentStateChanged += media_CurrentStateChanged;
    
    
    private void media_CurrentStateChanged(object sender, RoutedEventArgs e)
    {
        switch (media.CurrentState)
        {
            case MediaElementState.AcquiringLicense:
                break;
            case MediaElementState.Buffering:
                break;
            case MediaElementState.Closed:
                break;
            case MediaElementState.Individualizing:
                break;
            case MediaElementState.Opening:
                break;
            case MediaElementState.Paused:
                break;
            case MediaElementState.Playing:
                break;
            case MediaElementState.Stopped:
                break;
            default:
                break;
        }
    }
    

    You can use this to detect the current state of the media.. Hope it helps..