Play MP3 Files in Windows with Python

Portions of this post were previously published on Sun, 26 Jun 2011.

I 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.

As an early experiment, I rewrote in Python the bulk of the command-line MP3 player I had originally written in C. Please refer to the script below:

playmp3.py

# Copyright (c) 2022 by James K. Lawless
# jimbo@radiks.net
# License: MIT / X11
# See: http://jimlawless.net/license2022.php
# for full license details.
 
import argparse 
from ctypes import *
from sys import getfilesystemencoding

winmm = windll.winmm
filesystemencoding = getfilesystemencoding()

def mciSend(s):
    enc=s.encode(filesystemencoding)    
    i=winmm.mciSendStringA(enc,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")
    
if __name__ == "__main__":
    parser=argparse.ArgumentParser()
    parser.description="play an MP3 or WAV file"
    parser.add_argument("-file",required=True)
    args=parser.parse_args()
    playMP3(args.file)    

The Github repository for the above is at https://github.com/jimlawless/playmp3

usage: playmp3.py [-h] -file FILE
playmp3.py: error: the following arguments are required: -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.

A number of people using the original C program have reported issues with the above technique. The issues occur as “error 277” and/or “error 263”. These issues began to occur in Windows 7 which supplied its own audio compression / decompression drivers. The blog post below describes the issue. Scroll down to the bottom of the post for a potential solution:

http://www.vbforums.com/showthread.php?764359-RESOLVED-API-mciSendString-type-MPEGVideo-won-t-play-mp3-on-Windows-7

I’d also recently discovered that if you use WAV files as arguments instead of MP3 files, Windows still seems to play them. That’s kind of a nice feature they added on my behalf!