Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Media Play/Pause Simulation

Tags:

python

windows

My keyboard contains a row of buttons for various non-standard keyboard tasks. These keys contain such functions as modifying the volume, playing or pausing, and skipping tracks. How can I simulate a basic play/pause with Python? I am on Windows, by the way.

like image 291
Paul Avatar asked May 04 '12 00:05

Paul


1 Answers

I would use pywin32. Bundled with the installation is a large number of API-docs (usually placed at something like C:\Python32\Lib\site-packages.) It essentially wraps a lot of stuff in the Win32-library which is used for many low-levels tasks in Windows.

After installing it you could use the wrapper for keybd_event.

You could also use SendInput instead of keybd_event but it doesn't seem to be wrapped by PyWin32. SendMessage is also an option but more cumbersome.

You'll need to look up the virtual scan code for those special buttons, since I doubt the char-to-code mapping functions will help you here. You can find the reference here.

Then it is a simple matter of calling the function. The snippet below pauses Chuck Berry on my computer.

>>> import win32api
>>> VK_MEDIA_PLAY_PAUSE = 0xB3
>>> hwcode = win32api.MapVirtualKey(VK_MEDIA_PLAY_PAUSE, 0)
>>> hwcode
34
>>> win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, hwcode)

MapVirtualKey gives us the hardware scan code which keybd_event needs (or more likely, the keyboard driver.)

Note that all this is snapped up by the keyboard driver, so you don't really have any control where the keystrokes are sent. With SendMessage you can send them to a specific window. It usually doesn't matter with media keys since those are intercepted by music players and such.

like image 119
Skurmedel Avatar answered Nov 04 '22 21:11

Skurmedel