Charles Mills

Technical musings of an unemployable ginger.

Playing audio in Python with libVLC Python Audio VLC

Sat 01 March 2014

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.

Embarrassing First Post Python Useless

Fri 28 February 2014

This post serves no purpose other than to fill the inevitable void. Last week at an interview I was asked to write a Fibonacci function, it seems regurgitation of Computer Science theory makes you employable, so here they are in Python.


def f(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
        return f(n-1) + f(n-2)


def f(n):
    a = 0
    b = 1
    for i in range(0, n):
        a, b = b, a + b
    return a

Please revel in the usefulness of these numbers (excuse the bitterness).