Play MP3 Files with Python ( Windows )

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:

playmp3.py

# Copyright (c) 2011 by James K. Lawless
# jimbo@radiks.net 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

http://www.mailsend-online.com/wp/playmp3.zip

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.

Advertisements

About Jim Lawless

I've been programming computers for about 36 years ... 30 of that professionally. I've been a teacher, I've worked as a consultant, and have written articles here and there for publications like Dr. Dobbs Journal, The C/C++ Users Journal, Nuts and Volts, and others.
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s