Originally published on: Sun, 26 Jun 2011.
I’ve just read the book Grey Hat Python : Python Programming for Hackers and Reverse Engineers by Justin Seitz. The book introduced the Python ctypes library to me. The ctypes library, allows a Python program to access to lower-level features of the operating environment normally reserved for C programmers.
( The book itself was a great read that deserves its own post … after I’ve had time to tinker with all of the code. )
As an early experiment, I rewrote in Python the bulk of the command-line MP3 player I had originall written in C. Please refer to the script below:
# Copyright (c) 2011 by James K. Lawless # email@example.com http://www.mailsend-online.com # License: MIT / X11 # See: http://www.mailsend-online.com/license.php # for full license details. from ctypes import *; winmm = windll.winmm def mciSend(s): i=winmm.mciSendStringA(s,0,0,0) if i<>0: print "Error %d in mciSendString %s" % ( i, s ) def playMP3(mp3Name): mciSend("Close All") mciSend("Open \"%s\" Type MPEGVideo Alias theMP3" % mp3Name) mciSend("Play theMP3 Wait") mciSend("Close theMP3") playMP3("test.mp3")
The ZIP archive containing the above source can be downloaded from
Note that the above script does not play a script directly from the command-line; it exposes the function playMP3() which should allow one to write Python code to control the invocation of the given MP3 file through the Media Control Interface (MCI).
The script expects a file named test.mp3 to be present in the current directory. You can alter the last line of the script, substituting the name and location of a preferred MP3 file.
Please note that in the Python version of the code, I have omitted the call to the Win32 API function GetShortPathName(). Instead, I placed double-quotes around the name of the MP3 file in the MCI command-string to accommodate the occurrences of spaces in the filename and/or pathname.