WPF: Implementing a MediaPlayer Audio / Video Seeker

12,496

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 :)

Share:
12,496
Andreas Grech
Author by

Andreas Grech

+++++[>+++++[>++++<-]<-]>>+++.--..++++++. Contactable at $(echo qernfterpu#tznvy?pbz | tr ?a-z# .n-za-m@)

Updated on June 07, 2022

Comments

  • Andreas Grech
    Andreas Grech almost 2 years

    I am currently working on an MP3 player (in a WPF application) with a WPF MediaPlayer and basically, I want to implement a Song Seeker which moves along with the current playing song.

    I already implemented a song slider (from Sacha Barber's application) and it works when the user drags the seeker manually (as in, the song continues from that position) but I cannot figure out how to make the seeker move according to the current position in the song.

    Trouble is I don't think there is a way to check when the Position property of the MediaPlayer has changed, so I'm stumped as to how I should implement this feature.

    Any ideas on how to go about such an issue?

    [Update]

    As regards incrementing the seeker with a timer, I actually thought of using the reason I didn't try it yet is because I think there is a better way to implement this using the MediaTimeline...but I'm yet to figure out how.