C# MediaPlayer.MediaEnded event not firing

情到浓时终转凉″ 提交于 2019-12-12 01:58:18

问题


i have this little piece of C# code

//Creates a MediaPlayer with the sound you want to play
    public static void PlaySound (Stream wavStream, string wavName, bool loop)
    {
        //Get the path for the file to play
        var path = GetFilePath(wavStream, wavName);

        var player = new MediaPlayer();
        player.Open(new Uri(path));
        player.MediaEnded += loop ? new EventHandler(MediaEndedLoop) : new EventHandler(MediaEndedDestroy);
        player.Play();

        players.Add(player);
        names.Add(wavName);
    }

I dont know why but MediaEndedLoop and MediaEndedDestroy are never called

Any idea?


回答1:


I also had this problem. I couldn't find a solution, but I did come up with a workaround if your media exists in a looping application or thread. You can just manually reset the position after a certain point.

if (media.Position > new TimeSpan(0, 2, 25))
      {
          media.Position = new TimeSpan(0, 0, 00);
      }

That's the best I can offer as of now.




回答2:


The MediaPlayer requires a Dispatcher in order to dispatch the MediaEnded, MediaOpened ... events.

When you are using a WinForm application a Dispatcher should already have been registered. That means that you should not have to do anything to get the events working.

If you want to receive events in a console application you'll have to run the Dispatcher yourself.

public static void Main (string[] args)
{
  var mediaPlayer = new MediaPlayer();
  mediaPlayer.MediaEnded += (sender, eventArgs) => Console.WriteLine ($"ended.");
  mediaPlayer.MediaOpened += (sender, eventArgs) => Console.WriteLine ($"started.");
  mediaPlayer.MediaFailed += (sender, eventArgs) => Console.WriteLine ($"failed: {eventArgs.ErrorException.Message}");
  mediaPlayer.Changed += (sender, eventArgs) => Console.WriteLine ("changed");

  mediaPlayer.Open (new Uri (@"S:\custom.mp3"));
  mediaPlayer.Play();

  Dispatcher.Run();
}


来源:https://stackoverflow.com/questions/38436779/c-sharp-mediaplayer-mediaended-event-not-firing

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