WPF MediaPlayer:如何按顺序播放,同步?

我有这个function:

public static void Play(string FileName, bool Async = false) { System.Windows.Media.MediaPlayer mp = new System.Windows.Media.MediaPlayer(); mp.Open(FileName.ToUri()); mp.Play(); } 

我打电话的时候

 Play(@"file1.mp3"); Play(@"file2.mp3"); Play(@"file3.mp3"); Play(@"file4.mp3"); 

他们都在同一时间玩。

如何让MediaPlayer等待文件结束,播放下一个? function应该是什么样的?

编辑:

 public static void Play(Uri FileName, bool Async = false) { AutoResetEvent a = new AutoResetEvent(false); MediaPlayer mp = new MediaPlayer(); mp.MediaEnded += (o1, p1) => { a.Set(); }; mp.MediaOpened += (o, p) => { int total = Convert.ToInt32(mp.NaturalDuration.TimeSpan.TotalMilliseconds); mp.Play(); if (!Async) { //System.Threading.Thread.Sleep(total); a.WaitOne(); } }; mp.Open(FileName); } 

在下一次调用Play之前,您需要等待当前文件完成播放。

这是通过收听MediaEnded事件来实现的。

你需要听取这个事件:

 mp.MediaEnded += MediaEndedEventHandler; 

但是,您需要将MediaPlayer对象设置为静态,这样您才能拥有其中一个。 确保只添加此处理程序一次。 然后在处理程序中发出一个新事件以开始播放下一个文件。

您正在实施的是播放列表。 因此,您将文件添加到播放列表中,然后您需要跟踪播放列表中的当前位置。

我将与您分享我的解决方案:

我创建了一个Window:WindowPlay.xaml

      

WindowPlay.xaml.cs:

 using System; using System.Windows; namespace Sistema.Util { ///  /// Interaction logic for WindowPlay.xaml ///  public partial class WindowPlay : Window { public WindowPlay() { try { InitializeComponent(); } catch { this.Close(); } } ///  /// Plays the specified file name ///  /// The filename to play /// If True play in background and return immediatelly the control to the calling code. If False, Play and wait until finish to return control to calling code. public static void Play(Uri FileName, bool Async = false) { WindowPlay w = new WindowPlay(); var mp = w.MediaElement1; if (mp == null) { // pode estar sendo fechada a janela return; } mp.Source = (FileName); if (Async) w.Show(); else w.ShowDialog(); } private void MediaElement1_MediaEnded(object sender, RoutedEventArgs e) { this.Close(); } } }