使用设置的开始时间码将时间码转换为帧

时间:2016-01-05 07:11:41

标签: python-2.7 timecodes

我使用下面的脚本将时间码转换为帧,但是只能使用00:00:00:00的开始时间码进行转换。我希望能够设置开始时间码,因此计算是相对的。如果我将帧速率设置为23.976或29.97,它也会中断。

framerate = 24

def timecode_to_frames(timecode):
    return sum(f * int(t) for f,t in zip((3600*framerate, 60*framerate, framerate, 1), timecode.split(':')))

def frames_to_timecode(frames):
    return '{0:02d}:{1:02d}:{2:02d}:{3:02d}'.format(frames / (3600*framerate),
                                                    frames / (60*framerate) % 60,
                                                    frames / framerate % 60,
                                                    frames % framerate)

print timecode_to_frames('00:00:00:10')
print frames_to_timecode(10)

1 个答案:

答案 0 :(得分:2)

如果您首先将值转换为数字(例如秒),则可以轻松地进行算术运算:

framerate = 23.976

def _seconds(value):
    if isinstance(value, str):  # value seems to be a timestamp
        _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
        return sum(f * float(t) for f,t in _zip_ft)
    elif isinstance(value, (int, float)):  # frames
        return value / framerate
    else:
        return 0

def _timecode(seconds):
    return '{h:02d}:{m:02d}:{s:02d}:{f:02d}' \
            .format(h=int(seconds/3600),
                    m=int(seconds/60%60),
                    s=int(seconds%60),
                    f=round((seconds-int(seconds))*framerate))


def _frames(seconds):
    return seconds * framerate

def timecode_to_frames(timecode, start=None):
    return _frames(_seconds(timecode) - _seconds(start))

def frames_to_timecode(frames, start=None):
    return _timecode(_seconds(frames) + _seconds(start))


print(timecode_to_frames('00:00:18:10', start='00:00:05:15'))  # ~ 307
print(frames_to_timecode(307, start='00:00:05:15'))  # '00:00:18:10'