3

How can I get song name from internet radio stream?

Python: Get name of shoutcast/internet radio station from url I looked here, but there is only getting name of radio station. But how to get name of the playing song? Here is stream link from where I want to get name of song. http://pool.cdn.lagardere.cz/fm-evropa2-128

How should I do it? Can you help me please?

Community
  • 1
  • 1
Václav Pavlíček
  • 419
  • 2
  • 9
  • 21
  • 1
    Did you see this? http://anton.logvinenko.name/en/blog/how-to-get-title-from-audio-stream-with-python.html – Kamil Wozniak Jan 30 '16 at 13:27
  • related: [Developing the client for the icecast server](http://stackoverflow.com/q/6061057/4279) – jfs Jan 30 '16 at 17:07

1 Answers1

9

To get the stream title, you need to request metadata. See shoutcast/icecast protocol description:

#!/usr/bin/env python
from __future__ import print_function
import re
import struct
import sys
try:
    import urllib2
except ImportError:  # Python 3
    import urllib.request as urllib2

url = 'http://pool.cdn.lagardere.cz/fm-evropa2-128'  # radio stream
encoding = 'latin1' # default: iso-8859-1 for mp3 and utf-8 for ogg streams
request = urllib2.Request(url, headers={'Icy-MetaData': 1})  # request metadata
response = urllib2.urlopen(request)
print(response.headers, file=sys.stderr)
metaint = int(response.headers['icy-metaint'])
for _ in range(10): # # title may be empty initially, try several times
    response.read(metaint)  # skip to metadata
    metadata_length = struct.unpack('B', response.read(1))[0] * 16  # length byte
    metadata = response.read(metadata_length).rstrip(b'\0')
    print(metadata, file=sys.stderr)
    # extract title from the metadata
    m = re.search(br"StreamTitle='([^']*)';", metadata)
    if m:
        title = m.group(1)
        if title:
            break
else: 
    sys.exit('no title found')
print(title.decode(encoding, errors='replace'))

The stream title is empty in this case.

jfs
  • 399,953
  • 195
  • 994
  • 1,670