WPF: Implementing a MediaPlayer Audio / Video Seeker

此生再无相见时 提交于 2019-11-30 10:37:48

ARISE answer! and serve your master

OK, I've figured out how to work this. I'm sure I'm not doing it the completely correct way but it does work.

Here is the code-behind of a WPF application, with a Pause/Play button.

public partial class Main : Window
{
    MediaPlayer MPlayer;
    MediaTimeline MTimeline;

    public Main()
    {
        InitializeComponent();

        var uri = new Uri("C:\\Test.mp3");
        MPlayer = new MediaPlayer();
        MTimeline = new MediaTimeline(uri);
        MTimeline.CurrentTimeInvalidated += new EventHandler(MTimeline_CurrentTimeInvalidated);
        MPlayer.Clock = MTimeline.CreateClock(true) as MediaClock;
        MPlayer.Clock.Controller.Stop();
    }

    void MTimeline_CurrentTimeInvalidated(object sender, EventArgs e)
    {
        Console.WriteLine(MPlayer.Clock.CurrentTime.Value.TotalSeconds);
    }

    private void btnPlayPause_Click(object sender, RoutedEventArgs e)
    {
        //Is Active
        if (MPlayer.Clock.CurrentState == ClockState.Active)
        {
            //Is Paused
            if (MPlayer.Clock.CurrentGlobalSpeed == 0.0)
                MPlayer.Clock.Controller.Resume();
            else //Is Playing
                MPlayer.Clock.Controller.Pause();
        }
        else if (MPlayer.Clock.CurrentState == ClockState.Stopped) //Is Stopped
            MPlayer.Clock.Controller.Begin();
    }
}

The trick is that once you set the clock of a MediaPlayer, it becomes clock controlled, thus the use of MPlayer.Clock.Controller to do all of the controlling :)

Never played with media player but assuming you know the length of song could you not setup a timer that ticks every second while the song is playing. Therefore for every tick just increment the seeker in relation to how long the song is in total.

Song is 100 seconds long. Therefore every second/tick is worth 1 percent of total progress.

You'd have to stop the timer when pausing song etc...

MediaElement has a position property which you could use for this: http://msdn.microsoft.com/en-us/library/system.windows.controls.mediaelement.position.aspx

Have you checked out the WPF MediaKit yet?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!