Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Way to check whether internet radio stream is avaliable/live

I work on collecting internet radio stream files such as m3u with a link to stream inside (for example http://aska.ru-hoster.com:8053/autodj).

I didn`t find example on how it is possible to check if the link is avaliable/live.

Any help is appreciated!

UPD:

Maybe the main question should sound like:

Could be a stream broken? If yes, will the link for that stream be still available or there will be simply 404 error in browser? If link still available to open even stream is dead, what are other methods to check the stream?

like image 949
Michael Avatar asked Oct 17 '22 06:10

Michael


1 Answers

Are you trying to check if the streaming URL exists?
If yes, it will be just like checking any other url if it exists.

One way will be to try getting url using urllib and check for returned status code.

200 - Exists
Anything else (e.g. 404) -Doesn't exist or you can't access it.

For example:

import urllib
url = 'http://aska.ru-hoster.com:8053/autodj'

code = urllib.urlopen(url).getcode()
#if code == 200:  #Edited per @Brad's comment
 if str(code).startswith('2') or str(code).startswith('3') :
    print 'Stream is working'
else:
    print 'Stream is dead'

EDIT-1

While above will catch if a URL exists or not. It will not catch if URL exists and media link is broken.

One possible solution using vlc is to get the media from url, try to play it and get its status while playing. If media doesnt exists, we will get error which can be used to determine link status.

With working URL we get

url = 'http://aska.ru-hoster.com:8053/autodj'
>>> 
Stream is working. Current state = State.Playing   

With broken URL we get,

url = 'http://aska.ru-hoster.com:8053/autodj12345'
>>> 
Stream is dead. Current state = State.Error

Below is basic logic to achieve above. You may want to check VLC site to catch other error types and better methods.

import vlc
import time

url = 'http://aska.ru-hoster.com:8053/autodj'
#define VLC instance
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')

#Define VLC player
player=instance.media_player_new()

#Define VLC media
media=instance.media_new(url)

#Set player media
player.set_media(media)

#Play the media
player.play()


#Sleep for 5 sec for VLC to complete retries.
time.sleep(5)
#Get current state.
state = str(player.get_state())

#Find out if stream is working.
if state == "vlc.State.Error" or state == "State.Error":
    print 'Stream is dead. Current state = {}'.format(state)
    player.stop()
else:
    print 'Stream is working. Current state = {}'.format(state)
    player.stop()
like image 117
Anil_M Avatar answered Nov 03 '22 07:11

Anil_M