Home get reference of new dynamicly created MediaPlayer instance
Reply: 1

get reference of new dynamicly created MediaPlayer instance

A.ALMUSBAHI
1#
A.ALMUSBAHI Published in 2018-01-10 08:50:58Z

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)

Sunil
2#
Sunil Reply to 2018-01-10 10:40:29Z

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();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312116 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO