1

我住在世界的另一端(现在是 GMT+1,现在是 GMT+13),我想念我以前的地面广播电台。它有一个 Shoutcast 流,我想简单地将它延迟 12 小时,以便在我想收听它时它始终可用,以使其时区与我的时区同步的方式。

我将其设想为在我的服务器主机上运行的脚本。

一种天真的方法只是在环形缓冲区中分配足够的内存来存储整个 12 小时的延迟,并通过管道输入 streamripper 的输出。但是流是 128kbps 的 mp3,这意味着 (128/8) * 60 * 60 = ~56MB/小时,或者整个 12 小时缓冲区的 675MB,这并不是那么实用。另外,我可能不得不处理我的服务器主机,只是在某个超时后终止进程。

那么,有哪些实际可行的策略呢?

4

3 回答 3

1

你为什么不直接用 Ripshout 之类的流开膛手下载它呢?

于 2008-12-03T20:05:46.513 回答
1

流开膛手将是简单的方式,也可能是正确的方式,但如果你想用程序员的方式来做......

  • 大多数开发机器都有相当多的 RAM。你确定你不能腾出 675 MB 吗?
  • 不是将输出存储在缓冲区中,而是不能将其存储在一个或多个文件中,比如一次一个小时?(本质上,您将编写自己的流开膛手)
  • 如果您可以容忍质量损失,请将流转换为较低的比特率
于 2008-12-03T21:10:18.320 回答
0

为了回答我自己的问题,这里有一个脚本,它每 30 分钟启动一次 cron 作业。它将传入流以 5 分钟的块(或由 FILE_SECONDS 设置)转储到特定目录。块边界与时钟同步,直到当前时间块结束时才开始写入因此正在运行的 cronjobs 可以重叠而不会加倍数据或留下间隙。文件被命名为 (epoch time % number of seconds in 24 hours).str 。

我还没有制作播放器,但计划是将输出目录设置为可通过网络访问的某个位置,并编写一个在本地运行的脚本,该脚本使用与此处相同的时间戳计算代码来顺序访问(时间戳 12 小时前).str,将它们重新组合在一起,然后在本地设置为广播服务器。然后我可以将我的音乐播放器指向http://localhost:port并获取它。

编辑:具有超时和更好的错误条件检查的新版本,以及漂亮的日志文件。这目前在我的(便宜的)共享虚拟主机上运行顺利,没有问题。

#!/usr/bin/python
import time
import urllib
import datetime
import os
import socket

# number of seconds for each file
FILE_SECONDS = 300

# run for 30 minutes
RUN_TIME = 60*30

# size in bytes of each read block
# 16384 = 1 second
BLOCK_SIZE = 16384

MAX_TIMEOUTS = 10

# where to save the files
OUTPUT_DIRECTORY = "dir/"
# URL for original stream
URL = "http://url/path:port"

debug = True
log = None
socket.setdefaulttimeout(10)

class DatestampedWriter:

    # output_path MUST have trailing '/'
    def __init__(self, output_path, run_seconds ):
        self.path = output_path
        self.file = None
        # needs to be -1 to avoid issue when 0 is a real timestamp
        self.curr_timestamp = -1
        self.running = False
        # don't start until the _end_ of the current time block
        # so calculate an initial timestamp as (now+FILE_SECONDS)
        self.initial_timestamp = self.CalcTimestamp( FILE_SECONDS )
        self.final_timestamp = self.CalcTimestamp( run_seconds )
        if debug:
            log = open(OUTPUT_DIRECTORY+"log_"+str(self.initial_timestamp)+".txt","w")
            log.write("initial timestamp "+str(self.initial_timestamp)+", final "+str(self.final_timestamp)+" (diff "+str(self.final_timestamp-self.initial_timestamp)+")\n")

        self.log = log

    def Shutdown(self):
        if self.file != None:
            self.file.close()

    # write out buf
    # returns True when we should stop
    def Write(self, buf):
        # check that we have the correct file open

        # get timestamp
        timestamp = self.CalcTimestamp()

        if not self.running :
            # should we start?
            if timestamp == self.initial_timestamp:
                if debug:
                    self.log.write( "starting running now\n" )
                    self.log.flush()
                self.running = True

        # should we open a new file?
        if self.running and timestamp != self.curr_timestamp:
            if debug:
                self.log.write( "new timestamp "+str(timestamp)+"\n" )
                self.log.flush()
            # close old file
            if ( self.file != None ):
                self.file.close()
            # time to stop?
            if ( self.curr_timestamp == self.final_timestamp ):
                if debug:
                    self.log.write( " -- time to stop\n" )
                    self.log.flush()
                self.running = False
                return True
            # open new file
            filename = self.path+str(timestamp)+".str"
            #if not os.path.exists(filename):
            self.file = open(filename, "w")
            self.curr_timestamp = int(timestamp)
            #else:
                # uh-oh
            #   if debug:
            #       self.log.write(" tried to open but failed, already there\n")
            #   self.running = False

        # now write bytes
        if self.running:
            #print("writing "+str(len(buf)))
            self.file.write( buf )

        return False

    def CalcTimestamp(self, seconds_offset=0):
        t = datetime.datetime.now()
        seconds = time.mktime(t.timetuple())+seconds_offset
        # FILE_SECONDS intervals, 24 hour days
        timestamp = seconds - ( seconds % FILE_SECONDS )
        timestamp = timestamp % 86400
        return int(timestamp)


writer = DatestampedWriter(OUTPUT_DIRECTORY, RUN_TIME)

writer_finished = False

# while been running for < (RUN_TIME + 5 minutes)
now = time.mktime(datetime.datetime.now().timetuple())
stop_time = now + RUN_TIME + 5*60
while not writer_finished and time.mktime(datetime.datetime.now().timetuple())<stop_time:

    now = time.mktime(datetime.datetime.now().timetuple())

    # open the stream
    if debug:
        writer.log.write("opening stream... "+str(now)+"/"+str(stop_time)+"\n")
        writer.log.flush()
    try:
        u = urllib.urlopen(URL)
    except socket.timeout:
        if debug:
            writer.log.write("timed out, sleeping 60 seconds\n")
            writer.log.flush()
        time.sleep(60)
        continue
    except IOError:
        if debug:
            writer.log.write("IOError, sleeping 60 seconds\n")
            writer.log.flush()
        time.sleep(60)
        continue
        # read 1 block of input
    buf = u.read(BLOCK_SIZE)

    timeouts = 0
    while len(buf) > 0 and not writer_finished and now<stop_time and timeouts<MAX_TIMEOUTS:
        # write to disc
        writer_finished = writer.Write(buf)

        # read 1 block of input
        try:
            buf = u.read(BLOCK_SIZE)
        except socket.timeout:
            # catch exception but do nothing about it
            if debug:
                writer.log.write("read timed out ("+str(timeouts)+")\n")
                writer.log.flush()
            timeouts = timeouts+1

        now = time.mktime(datetime.datetime.now().timetuple())
    # stream has closed,
    if debug:
        writer.log.write("read loop bailed out: timeouts "+str(timeouts)+", time "+str(now)+"\n")
        writer.log.flush()
    u.close();
    # sleep 1 second before trying to open the stream again
    time.sleep(1)

    now = time.mktime(datetime.datetime.now().timetuple())

writer.Shutdown()
于 2008-12-04T14:24:57.840 回答