Search code examples
c#windowsaudiomediakeyboard-events

How can I access and control the media sources playing on Windows in C#?


I would like to create a program that can manually change the priority of media being played on my PC using C#.

This is because the Play/Pause button on my keyboard does not stick to the program I want it to.

In my mind the media being played would be stored in a stack and I want to push the program I want to access to the top for the keyboard to Play/Pause it. The stack for example:

  • Spotify
  • YouTube (Chrome)
  • Netflix (Opera)

The item at the top (Spotify) would be the one accessed by the Play/Pause key.

I'm not sure how Windows handles this at all so any information would be greatly appreciated.

I haven't tried anything as I do not know where to start, or if this is even possible.


Solution

  • You can change the media priority in windows by getting the proccess and setting its priority like this :

    using System;
    using System.Diagnostics;
    
    namespace ProcessRealtime
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Define the names of the media processes
                string[] mediaProcesses = new string[] { "Spotify", "Chrome", "Opera" };
    
                // Loop through the media processes
                foreach (string mediaProcess in mediaProcesses)
                {
                    // Get the processes by name
                    Process[] processes = Process.GetProcessesByName(mediaProcess);
    
                    // Loop through the processes
                    foreach (Process proc in processes)
                    {
                        // Change the priority to RealTime
                        proc.PriorityClass = ProcessPriorityClass.RealTime;
    
                        // Print a message
                        Console.WriteLine("Changed priority for {0} to RealTime", proc.ProcessName);
                    }
                }
    
                // Wait for a key press
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
    

    You could then add something like a eventlistener for the defined key combinations so that you can switch the current prio.