Search code examples
c#audiosoundplayer

Do something after a music ends with SoundPlayer


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();
        }
    }

Solution

  • 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());