Media Play/Pause Simulation
Question: 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.


Answer: I would use
[pywin32](http://starship.python.net/crew/mhammond/win32/Downloads.html).
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](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms646304.aspx).

_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](http://msdn.microsoft.com/en-
us/library/windows/desktop/dd375731.aspx).

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.

