获取新动态创建的 Media Player 实例的引用

get reference of new dynamicly created MediaPlayer instance

我正在尝试创建一个 C# 应用程序,该应用程序动态创建了多个按钮,每个按钮都有 Click_Handler,如果单击它会根据用户之前指定的文件播放声音。

一切正常,使用这个简单的功能可以同时播放所有声音

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

现在,每次用户单击任何按钮时,它都会使用 MediaPlayer 对象的新实例开始播放声音

我的问题是如何获得对每个新创建的 MediaPlayer 对象的引用,以便我可以对其进行操作(停止、暂停、时间轴等)

只是return调用方法后的实例:

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

在您的调用代码中检查 returned 对象在使用之前是否不为空:

var mp = playSound(@"d:\music\file.mp3");
if(mp != null)
{
   //do something with mp
}

您也可以将此 MediaPlayer 对象保存在字典对象中以便于操作。

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