Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python simulate media keys

How to make Python (3.7) manipulate any media player currently working on Windows?

I want to get functionality similar to media keys on keyboard, for example:

  • play_pause.py script which will play or pause music on Spotify or movie in media player (whatever is currently playing).
  • play_next.py script which will play next song/movie etc.

To clarify: I don't want Python to virtually press actual media keys on keyboard. I would like to get the functionality of such keys so it might work even without keyboard connected to PC.

like image 216
SzalonyKefir Avatar asked Oct 12 '25 15:10

SzalonyKefir


1 Answers

The easiest solution is to use win32api.keybd_event from pywin32.

For example, install pywin32:

pip install pywin32

And try play/pause - should work without keyboard:

import win32api
from win32con import VK_MEDIA_PLAY_PAUSE, KEYEVENTF_EXTENDEDKEY

win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENDEDKEY, 0)

Virtual-Key Codes: here and here.

NOTE:
At this link about keybd_event function, you can see message: "Note This function has been superseded. Use SendInput instead".
So if you want/need to use SendInput, you probably need to use ctypes. I suggest you to check the example here. I've tried that code too and it works. If you need any further help, let me know.

like image 130
qwermike Avatar answered Oct 14 '25 03:10

qwermike