mad*_*aze 9 python stream radio audio-streaming
我正在寻找一个python片段来读取互联网广播流(.asx,.pls等)并将其保存到文件中.
最后的项目是cron'ed脚本,它将记录一两个小时的互联网广播,然后将其传输到我的手机上以便在我上下班时播放.(3g在我的通勤上有点不稳定)
欢迎任何snippits或指针.
Jaz*_*zer 10
以下对我使用请求库来处理http请求起了作用.
import requests
stream_url = 'http://your-stream-source.com/stream'
r = requests.get(stream_url, stream=True)
with open('stream.mp3', 'wb') as f:
try:
for block in r.iter_content(1024):
f.write(block)
except KeyboardInterrupt:
pass
Run Code Online (Sandbox Code Playgroud)
这将保存一个流到stream.mp3文件,直到你打断它ctrl+C.
因此,在修补和玩它之后,我发现Streamripper工作得最好.这是我使用的命令
streamripper http://yp.shoutcast.com/sbin/tunein-station.pls?id=1377200 -d ./streams -l 10800 -a tb$FNAME
Run Code Online (Sandbox Code Playgroud)
如果您发现Python3中的请求或urllib.request调用无法保存流,因为您收到"ICY 200 OK"而不是"HTTP/1.0 200 OK"标题,则需要告知基础函数ICY 200好的没关系!
您可以有效地执行的操作是在处理标头之前拦截打开流后处理状态的例程.
只需在您的流开放代码上面加上这样的例程.
def NiceToICY(self):
class InterceptedHTTPResponse():
pass
import io
line = self.fp.readline().replace(b"ICY 200 OK\r\n", b"HTTP/1.0 200 OK\r\n")
InterceptedSelf = InterceptedHTTPResponse()
InterceptedSelf.fp = io.BufferedReader(io.BytesIO(line))
InterceptedSelf.debuglevel = self.debuglevel
InterceptedSelf._close_conn = self._close_conn
return ORIGINAL_HTTP_CLIENT_READ_STATUS(InterceptedSelf)
Run Code Online (Sandbox Code Playgroud)
然后在打开URL之前将这些行放在主例程的开头.
ORIGINAL_HTTP_CLIENT_READ_STATUS = urllib.request.http.client.HTTPResponse._read_status
urllib.request.http.client.HTTPResponse._read_status = NiceToICY
Run Code Online (Sandbox Code Playgroud)
它们将覆盖标准例程(仅此一次)并在打开流时运行NiceToICY函数代替正常状态检查.NiceToICY替换无法识别的状态响应,然后复制"真实"_read_status函数所需的原始响应的相关位.最后调用原始函数,并将其中的值传递回调用者,其他所有内容都正常继续.
我发现这是解决导致错误的状态消息问题的最简单方法.希望它对你也有用.