How do I determine if MediaElement is playing?

前端 未结 8 2189
闹比i
闹比i 2021-01-01 09:44

Seems simple enough, but I cannot figure out any way to determine what the state of a MediaElement is. There are various properties for some states (such as IsBuffering) but

相关标签:
8条回答
  • 2021-01-01 10:15

    You can get at the _currentState member using reflection.

        private MediaState GetMediaState(MediaElement myMedia)
        {
            FieldInfo hlp = typeof(MediaElement).GetField("_helper", BindingFlags.NonPublic | BindingFlags.Instance);
            object helperObject = hlp.GetValue(myMedia);
            FieldInfo stateField = helperObject.GetType().GetField("_currentState", BindingFlags.NonPublic | BindingFlags.Instance);
            MediaState state = (MediaState)stateField.GetValue(helperObject);
            return state;
        }
    

    This covers play/pause, but doesn't change from 'play' to 'stop' when it finishes.

    You can get around this by adding an event handler to the MediaEnded event, and running the .Stop() method, this changes the status correctly (which can be picked up by the method above)

    0 讨论(0)
  • 2021-01-01 10:15

    And based on Rich S an extension can be implement

    //don't forget
    using System.Windows.Controls;
    using System.Reflection;
    
    
     public static class Util
        {
         public static MediaState GetMediaState(this MediaElement myMedia)
            {
                FieldInfo hlp = typeof(MediaElement).GetField("_helper", BindingFlags.NonPublic | BindingFlags.Instance);
                object helperObject = hlp.GetValue(myMedia);
                FieldInfo stateField = helperObject.GetType().GetField("_currentState", BindingFlags.NonPublic | BindingFlags.Instance);
                MediaState state = (MediaState)stateField.GetValue(helperObject);
                return state;
            }
        }
    
    0 讨论(0)
  • 2021-01-01 10:15

    For WPF use this: var playing = player.Position < player.NaturalDuration;

    0 讨论(0)
  • 2021-01-01 10:16

    What I did to "work around" that was subclass MediaPlayer (this would work for MediaElement as well) and add my own methods to Play/Pause/Stop. In those methods, I maintain a field which represents the playback status. Also, you need to hook MediaEnded so that you can change the status from 'playing' to 'stopped.'

    0 讨论(0)
  • 2021-01-01 10:20

    For Silverlight use CurrentState to check whether the state is playing or pause

     if (YourMediaElementName.CurrentState == MediaElementState.Playing)
     {
         // TODO: when media is playing.
     }
    
    0 讨论(0)
  • 2021-01-01 10:26

    You aren't missing anything. You pretty much have to manually keep track of whether or not the media is playing. It's a pity, since it is so easy in Silverlight, as you mention. Seems like a major oversight to me.

    0 讨论(0)
提交回复
热议问题