Playing audio in Python with libVLC

Sat 01 March 2014

Posted by: Charlie Mills

Python Audio VLC

Libvlc is the library which is behind VLC, it is an incredibly stable and feature packed library with builds for pretty much every platform. More recently it has been relicensed from GPL to LGPL, allowing it to be used in proprietary projects. Unlike other audio playback libraries, libvlc is incredibly well documented, making it particularly good for beginners.

With every libvlc release, Python bindings are automatically generated. These bindings are based on ctypes which allows them to be used with pypy and other python implementations.

Libvlc provides the same support for codecs and formats as VLC player, making it a simple process to play virtually any format using the Python bindings. The first step is to download the bindings, adding them to your project directory.

wget --output-document ";a=blob_plain;f=generated/;hb=HEAD"

We can then import vlc and start using it.

import vlc
import time

instance = vlc.Instance()

#Create a MediaPlayer with the default instance
player = instance.media_player_new()

#Load the media file
media = instance.media_new('test.mp3')

#Add the media to the player

#Play for 10 seconds then exit

This code will create a livvlc instance, load the "test.mp3" file and play it for 10 seconds. Whilst the media is playing position and volume can be adjusted.

#set the player position to be 50% in

#Reduce the volume to 70%

We also have access to all of VLCs streaming features, suppose we wanted to stream a track over UDP whilst also playing it from speakers, this could be achieved by doing the following:

#Build vlc option string
options = 'sout=#duplicate{dst=rtp{access=udp,mux=ts,dst=,port=1233},dst=display}'

#Load media with streaming options
media = instance.media_new('test.mp3', options)

The above snippet will stream to the multicast address, allowing all devices on the network to consume the RTP stream, whilst also playing it locally.