2

I need to do something after my Async Loaded music file finishes. Let's say I want the program to exit or something. Now how do I make it do is after the music finishes?

    private void button1_Click(object sender, EventArgs e)
    {
        player.SoundLocation = @"Music\" + FileList[0];
        player.LoadAsync();
    }

    private void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (player.IsLoadCompleted)
        {
            player.PlaySync();
        }
    }
The Codesee
  • 3,714
  • 5
  • 38
  • 78
Tom Lenc
  • 765
  • 1
  • 17
  • 41

2 Answers2

2

Since the PlaySync method is synchronous then it will not return until the file has been played to the end. So, you can simply do it like this:

if (player.IsLoadCompleted)
{
    player.PlaySync();
    DoSomethingAfterMusicIsDone();
}

UPDATE:

LoadAsync seems to run synchronously if the SoundLocation points to a file on the file system. This means that you should invoke LoadAsync on another thread if you don't want to freeze the UI thread. Here is an example:

Task.Run(() => player.LoadAsync());
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
  • If I understood it right... async load makes it run on a different thread so it wont freeze the window... that means... that it's like thread.sleep, which stays there for the specified ammount of time.. is it something like this? – Tom Lenc Dec 03 '15 at 19:28
  • @TomLenc, I am not sure I understand your question. async means you don't keep waiting for the thing to complete. – Yacoub Massad Dec 03 '15 at 19:32
0

Use MediaPlayer instead:

mediaPlayer = new MediaPlayer();
mediaPlayer.MediaEnded += delegate { MessageBox.Show("Media Ended"); };
mediaPlayer.Open(new Uri(@"C:\myfile.mp3"));
mediaPlayer.Play();

Sounds good in theory. However, in truth, I couldn't get the MediaEnded Event to fire. Thus, I had to poll for the end of MediaEvent as follows:

while(true)
{
    System.Threading.Thread.Sleep(1000);
    string pos = "unknown";
    string dur = "unknown";

    try 
    {
        pos = mediaplayer1.Position.Ticks.ToString();
        dur = mediaplayer1.NaturalDurataion.TimeSpan.Ticks.ToString()
        if (pos == dur)
        {
            // MediaEnded!!!!!
            pos = "0";
            dur = "0";
        }
        catch {}
    }
}

On the positive side, you can update your Audio player Slider by polling... On the downside, it makes the pause button a little bit unresponsive if you notice 1000 milliseconds lag...

If you use this workaround, I would recommend placing the Mediaplayer in a background thread so that the polling loop doesn't lock up the UI thread.

Bimo
  • 5,987
  • 2
  • 39
  • 61