本文介绍了C#MediaPlayer.MediaEnded事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这小段C#代码

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

我不知道为什么,但是从未调用MediaEndedLoop和MediaEndedDestroy

I dont know why but MediaEndedLoop and MediaEndedDestroy are never called

有什么主意吗?

推荐答案

MediaPlayer 需要一个 Dispatcher ,以便分派 MediaEnded MediaOpened ...事件.

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

使用WinForm应用程序时,应该已经注册了 Dispatcher .这意味着您无需执行任何操作即可使事件正常运行.

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.

如果要在控制台应用程序中接收事件,则必须自己运行 Dispatcher .

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

这篇关于C#MediaPlayer.MediaEnded事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:26