C# MediaPlayer.MediaEnded event not firing

后端 未结 2 1095
天命终不由人
天命终不由人 2021-01-28 20:25

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, b         


        
2条回答
  •  青春惊慌失措
    2021-01-28 20:49

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

提交回复
热议问题