Thursday, July 9, 2009

Playing an MP3 with pyglet and Python is easy

By Vasudev Ram

pyglet is a cross-platform windowing and multimedia library for Python.

Playing an MP3 with pyglet and Python is as easy as this:

import pyglet

music ='your_file.mp3')

Some of the features of pyglet (from the pyglet site):

  • No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation.

  • Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games.

  • Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid.

Another good thing about pyglet is that it's a small download; also, installation went fast and without a hitch. Immediately after installing it (on Windows, with the bundled AVBin), I was able to run the above code. No configuration was required. AVbin is a thin wrapper around FFmpeg, which is a cross-platform solution to record, convert and stream audio and video.

I've not yet checked whether it's possible to pause and continue the played audio, though, either programmatically or via some graphical controls of pyglet.

UPDATE: Yes, GUI controls are possible. See the code for this audio and video player with simple GUI controls, in the link titled "examples/" near the end of this page.

Currently listening to an MP3 of a tech interview that's being played by the above pyglet program.

- Vasudev Ram - Dancing Bison Enterprises.

No comments: