Search code examples
c#winformsaudiomedia-player

get reference of new dynamicly created MediaPlayer instance


I am trying to create a C# app that have dynamically created number of buttons , each button have Click_Handler that if clicked plays a sound depending on a file that the user specified earlier.

every thing is working and all the sounds plays at the same time using this simple function

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

Now each time a user clicks on any button it will start playing sound using new instance of the MediaPlayer object

My question is how can I get a reference to each newly created MediaPlayer object so that I can manipulate it (stop,pause,timeline ...etc)


Solution

  • Just return the instance after calling the method:

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

    In your calling code check if returned object is not null before using:

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

    You can also keep this MediaPlayer object in a dictionary object for easy manipulation.

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