Do something after a music ends with SoundPlayer

て烟熏妆下的殇ゞ 提交于 2019-12-24 16:28:33

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/34073945/do-something-after-a-music-ends-with-soundplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!