I have this function:
public static void Play(string FileName, bool Async = false)
{
System.Windows.Media.MediaPlayer mp = new System.Windows.Med
You need to wait for the current file to finish playing before calling Play
on the next.
This you do by listening for the MediaEnded event.
You'll need to listen for the event:
mp.MediaEnded += MediaEndedEventHandler;
However, you'll need to make the MediaPlayer
object a static too so you only ever have one of them. Make sure you only add this handler the once. Then in the handler issue a new event to start playing the next file.
What you are implementing is a playlist. So you'll add the files to the playlist and then you'll need to keep a track of your current position in the playlist.
I will share my Solution with you:
I created a Window: WindowPlay.xaml
<Window x:Class="Sistema.Util.WindowPlay"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowPlay"
AllowsTransparency="True"
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="0"
ResizeMode="NoResize"
WindowStyle="None"
Top="0" Left="0"
Width="16" Height="16"
ShowActivated="False"
ShowInTaskbar="False"
>
<Grid>
<MediaElement Name="MediaElement1" LoadedBehavior="Play" UnloadedBehavior="Close"
MediaEnded="MediaElement1_MediaEnded" />
</Grid>
</Window>
WindowPlay.xaml.cs:
using System;
using System.Windows;
namespace Sistema.Util
{
/// <summary>
/// Interaction logic for WindowPlay.xaml
/// </summary>
public partial class WindowPlay : Window
{
public WindowPlay()
{
try
{
InitializeComponent();
}
catch
{
this.Close();
}
}
/// <summary>
/// Plays the specified file name
/// </summary>
/// <param name="FileName">The filename to play</param>
/// <param name="Async">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.</param>
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();
}
}
}