我有一些代码可以查询广播流中的元数据。它将当前正在播放的歌曲(艺术家-标题)放入一个效果很好的变量中。我想使此脚本连续执行,但仅在歌曲改变时才执行。例如,脚本正在运行...当前正在播放的歌曲是“艺术家1-标题1”,并存储在now_playing中,随着脚本的运行,我希望它检测到now_playing何时实际上不同于之前的内容并执行一个事件
#!/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://soundcheck.xyz:8000' # 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)
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')
# 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("Now Playing:" + title.decode(encoding, errors='replace'))
print("Previous Song:" + last_song)
答案 0 :(得分:0)
您可以创建一个永远运行的循环:
prev_song = ""
while True:
# Your code to download song goes here.......
# Only print the result if changed
if title != prev_song:
prev_song = title
print("Now Playing:" + title.decode(encoding, errors='replace'))
# Sleep for a little bit before checking again
time.sleep(5)