using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Controls;
using System.IO;
using System.Windows.Forms;
namespace SoundBoard
{
class MediaPlayer
{
private MediaElement gPlayer = new MediaElement();
private bool gWillLoopMedia = false;
private bool gLoopBoxState = false; //is the loopbox on mainForm check
private string[] gPlayList;
public string gErrorMessage;
//Public constructor, used mainy to create the event handlers for the MediaElement.
public MediaPlayer()
{
gPlayer.MediaEnded += gPlayer_MediaEnded;
gPlayer.MediaFailed += gPlayer_MediaFailed;
}
void gPlayer_MediaFailed(object sender, System.Windows.ExceptionRoutedEventArgs e)
{
gErrorMessage = "The selected file ~1 could not be played"; //"~1" could be replaced with the file that caused the error to occur
}
public bool WillLoop
{
set { gWillLoopMedia = value; }
}
public bool IsLoopBoxCheck
{
set { gLoopBoxState = value; }
}
///
/// This method captures the MediaEnded event for the MediaElement and, if the playList array contains something,
/// it will remove the first object in the array, and pass the next object in as the param to the PlaySoundFile method.
/// The orginal array is replaced with this modified array.
///
///
///
void gPlayer_MediaEnded(object sender, System.Windows.RoutedEventArgs e)
{
//select next item in playlist
if (gPlayList != null)
{
//Easiest way to remove the object at index zero
List tempList = new List();
tempList = gPlayList.ToList();
tempList.RemoveAt(0);
gPlayList = tempList.ToArray();
if (gPlayList.Length > 0)
{
PlaySoundFile(gPlayList[0]);
}
else
{
//check to see if the loopbox on mainForm is checked
if (gLoopBoxState)
{
gWillLoopMedia = true;
}
else
{
gWillLoopMedia = false;
}
gPlayList = null; //null out the playList string array, so the playList isn't repeated by mistake
}
}
else
{
//If the playList variable is empty then it's safe to assume the randomize function is not active.
if (gWillLoopMedia)
{
gPlayer.Position = TimeSpan.Zero;
gPlayer.Play();
}
}
}
public void PlayAudioPlaylist(string[] playList)
{
gPlayList = null;
gWillLoopMedia = false;
gPlayList = playList;
PlaySoundFile(playList[0]);
}
public void PlaySoundFile(string file)
{
gPlayer.Source = new Uri(file);
gPlayer.LoadedBehavior = MediaState.Manual;
gPlayer.UnloadedBehavior = MediaState.Manual;
gPlayer.Play();
}
}
}