December 25, 2012 How to get title from an audio stream with Python

How to get the name of a song from an audio stream?

Most of audio streaming servers (Icecast, Shoutcast, etc.) use Shoutcast Metadata Protocol. This protocol have information about song title in audio stream with some byte shift. You can read about this in nice tutorial here.

Code example with python:

#!/usr/bin/env python
import urllib2
stream_url = 'http://pub1.di.fm/di_classictrance'
request = urllib2.Request(stream_url)
try:
    request.add_header('Icy-MetaData', 1)
    response = urllib2.urlopen(request)
    icy_metaint_header = response.headers.get('icy-metaint')
    if icy_metaint_header is not None:
        metaint = int(icy_metaint_header)
        read_buffer = metaint+255
        content = response.read(read_buffer)
        title = content[metaint:].split("'")[1]
        print title
except:
    print 'Error'
Development