Search code examples
c#wpfwmp

C# WPF Invoking Windows Media Player


I'm currently passing my time by creating a piano app. Each Key is represented of a simple button with a command which fires at click. This leads to executing this Method in ViewModel:

    private void PlaySound(object parameter)
    {
        var mediaPlayer = new MediaPlayer();
        mediaPlayer.Open(new System.Uri(@SoundBar.GetSoundPathByIdent(int.Parse(parameter.ToString()))));
        mediaPlayer.Play();
    {

I think the problem is that the MediaPlayer leaves a WeakReference which prevents the GarbageCollector from collecting it. Leading to overloading your RAM after playing a while.

The solution i found was to call: mediaPlayer.Close(); But this should only happen after the sound has finished playing, otherwise it will be cut.

Is there a way to check if the played sound has finished playing?

I have already spent some time doing research and testing but i couldn't come up with a working solution.


Solution

  • The Position and NaturalDuration properties give you details about where in the stream you're at (ie. Position / NaturalDuration gives you a value between 0.0 and 1.0 that represents the playback position as a percentage)

    But you may want to build an "orchestrator" for your media playback. Assuming that you don't want to play all sounds at the same time, an orchestrator could be responsible for managing the lifetime of your media players, and determining where in the playback they are.

    In your application you could create a single instance of the orchestrator on start up. The orchestrator could create and manage a pool of media players it could reuse when it needs to play a chord. Then your piano app could support a certain number of chords at the same time and have a single poller that determines which media players are free and which are "busy" playing audio.