3

I have a video file playing in a media element. I need to keep it playing, thus I tried:

me.play();
me.MediaEnded += new RoutedEventHandler(me_MediaEnded);

With this event method:

//loop to keep video playing continuously
void me_MediaEnded(object sender, EventArgs e)
{
    //play video again
    me.Play();
}

However the above does not replay the video file. Why? What did I do wrong?

4

4 回答 4

11

根据MSDN 上的帖子

Play() 从当前位置开始,因此您必须先到开始位置然后再播放。

所以你必须在重播之前重置位置:

me.Position = TimeSpan.FromSeconds(0);
me.Play();
于 2013-11-15T12:13:46.013 回答
2

我得到了它的工作:

class MyMediaPlayer : MediaPlayer
{
    private bool looping;

    public MyMediaPlayer() : base()
    {
        looping = false;  
        base.MediaEnded += new EventHandler(mediaEnded);
    }

    public MyMediaPlayer(string _file) : base()
    {
        looping = false;
        base.Open(new Uri(_file, UriKind.Relative));
        base.MediaEnded += new EventHandler(mediaEnded);
    }   

    public bool Looping
    {
        get { return looping;}
        set { looping = value; }
    }

    public void playLooping()
    {
        looping = true;
        base.Play();
    }

    public void playLooping(string _file)
    {
        looping = true;
        base.Open(new Uri(_file, UriKind.Relative));
        base.Play();
    }

    public void play()
    {
        looping = false;
        base.Play();
    }

    public void play(string _file)
    {
        looping = false;
        base.Open(new Uri(_file, UriKind.Relative));
        base.Play();
    }

    public void stop()
    {
        looping = false;
        base.Stop();
    }

    private void mediaEnded(object sender, EventArgs e)
    {
        if(looping)
        {
            base.Position = new TimeSpan(0, 0, 0);
            base.Play();
        }
    }

}

希望这能回答你的问题。

于 2015-04-10T02:10:56.917 回答
2

您还可以使用 Storyboard 来控制和循环播放视频,而无需挂钩事件或执行任何代码隐藏工作。这是 MSDN 上推荐的解决方案,对于 MVVM 设计来说是一个更优雅、更合适的解决方案。

在此处阅读有关 MSDN 的更多信息,包括示例:

http://msdn.microsoft.com/en-us/library/ms741866%28v=vs.100%29.aspx

于 2014-01-24T00:54:23.710 回答
1

我不知道原因,但这对我来说从来没有用过GIF:

me.Position = TimeSpan.FromSeconds(0);
me.Play();

我的 GIF 在第一次迭代后停止播放。

解决方案是:

<MediaElement x:Name="me"
              MediaEnded="MediaElement_MediaEnded"
              LoadedBehavior="Play" />

代码:

private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
    me.Position = TimeSpan.FromMilliseconds(1);
}

使用 1 毫秒,而 0 毫秒可能会停止播放,您无法使用“播放”方法再次运行它。

于 2014-10-21T13:22:28.990 回答