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

时光毁灭记忆、已成空白 提交于 2020-01-03 12:35:39

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/46099375/python-way-to-check-whether-internet-radio-stream-is-avaliable-live

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!