Mic*_*ael 5 python stream audio-streaming internet-radio python-3.x
我正在收集互联网广播流文件,例如m3u,其中包含一个流内部链接(例如http://aska.ru-hoster.com:8053/autodj).
我没有找到关于如何检查链接是否可用/实时的示例.
任何帮助表示赞赏!
UPD:
也许主要问题应该听起来像:
可能是一条小溪坏了吗?如果是,该流的链接是否仍然可用,或者浏览器中只会出现404错误?如果链接仍然可用于打开偶数流已经死亡,那么检查流的其他方法是什么?
您是否正在尝试检查流媒体 URL 是否存在?
如果是的话,就像检查其他 url 是否存在一样。
一种方法是尝试使用 urlurllib并检查返回的状态代码。
200 - 存在
其他任何内容(例如 404) - 不存在或您无法访问它。
例如:
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'
Run Code Online (Sandbox Code Playgroud)
编辑-1
上面的方法会捕获 URL 是否存在。如果 URL 存在且媒体链接已损坏,它将不会捕获。
一种可能的解决方案vlc是从 url 获取媒体,尝试播放它并在播放时获取其状态。如果媒体不存在,我们将收到错误消息,可用于确定链接状态。
通过工作 URL,我们得到
url = 'http://aska.ru-hoster.com:8053/autodj'
>>>
Stream is working. Current state = State.Playing
Run Code Online (Sandbox Code Playgroud)
通过损坏的 URL,我们得到,
url = 'http://aska.ru-hoster.com:8053/autodj12345'
>>>
Stream is dead. Current state = State.Error
Run Code Online (Sandbox Code Playgroud)
以下是实现上述目标的基本逻辑。您可能需要检查VLC 站点以捕获其他错误类型和更好的方法。
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()
Run Code Online (Sandbox Code Playgroud)