Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the MediaPlayer on repeat mode in C# WPF?

Tags:

c#

wpf

I have a MediaPlayer

public MediaPlayer backgroundMusicPlayer = new MediaPlayer ();

Now, because its background music, I'd like to repeat the song after its over.

How should I implement this?

This is what I found:

An event is raised when the song ends: backgroundMusicPlayer.MediaEnded

I am not sure what I should do about this? I am new to C# and programming in general.

EDIT:

public void PlaybackMusic ( )
{
    if ( backgroundMusicFilePath != null )
    {
         backgroundMusicPlayer.Open (new Uri (backgroundMusicFilePath));
         backgroundMusicPlayer.MediaEnded += new EventHandler (Media_Ended);
         backgroundMusicPlayer.Play ();

         return;
    }
}

private void Media_Ended ( object sender, EventArgs e )
{
    backgroundMusicPlayer.Open (new Uri (backgroundMusicFilePath));
    backgroundMusicPlayer.Play ();
}

This works, but I need to open the file every time. Is this the only way?

like image 915
user3080029 Avatar asked Jun 20 '14 05:06

user3080029


1 Answers

Instead of resetting the Source at the start of your Media_Ended handler, try setting the Position value back to the start position. The Position property is a TimeSpan so you probably want something like.

private void Media_Ended(object sender, EventArgs e)
{
    media.Position = TimeSpan.Zero;
    media.Play();
}

EDIT 1 : Find more details here

like image 150
Robert Langdon Avatar answered Nov 14 '22 23:11

Robert Langdon