调用方法后只需返回实例:
private System.Windows.Media.MediaPlayer playSound (string path)
{
if (System.IO.File.Exists(path))
{
System.Windows.Media.MediaPlayer mp = new System.Windows.Media.MediaPlayer();
mp.Open(new System.Uri(path));
mp.Play();
return mp;
}
return null;
}
在调用代码中,请在使用之前检查返回的对象是否不为null:
var mp = playSound(@"d:\music\file.mp3");
if(mp != null)
{
//do something with mp
}
您还可以将此MediaPlayer对象保存在dictionary对象中,以便于操作。
Dictionary<string, System.Windows.Media.MediaPlayer> players = new Dictionary<string, System.Windows.Media.MediaPlayer>();
var mp = playSound(@"d:\music\file.mp3");
players.Add(btn.Text, mp); //Identifying media player by button text
// Later if a user press the button again and your default action is pause
if(players.ContainsKey(btn.Text))
players[btn.Text].Pause();