5

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?

user3080029
  • 553
  • 1
  • 8
  • 19
  • What about [Settings.setMode(autoRewind)](http://msdn.microsoft.com/en-us/library/windows/desktop/dd564342%28v=vs.85%29.aspx)? – FoggyDay Jun 20 '14 at 05:27
  • Check with this answer and let us know if it works for you. http://stackoverflow.com/questions/5975388/c-sharp-wpf-how-to-repeat-mediaelement-playback-from-mediaended-event-handler-wi – Robert Langdon Jun 20 '14 at 05:29
  • @Robert - Sorry for being extremely dumb, but how is the Media_Ended function going to be called? I need to set up some mechanism right? This should work – user3080029 Jun 20 '14 at 05:35
  • Okay I got it, but I have to open the source file every time. – user3080029 Jun 20 '14 at 05:38
  • You just have to handle the event, plug-in the song and play it again. – Robert Langdon Jun 20 '14 at 05:40
  • you just need `backgroundMusicPlayer.Play();` in `backgroundMusicPlayer_MediaEnded` – Rang Jun 20 '14 at 05:42

1 Answers1

12

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

Community
  • 1
  • 1
Robert Langdon
  • 855
  • 1
  • 11
  • 27