WPF: Implementing a MediaPlayer Audio / Video Seeker

后端 未结 4 968
醉话见心
醉话见心 2021-01-01 06:15

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 th

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 06:44

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

提交回复
热议问题