python으로 만든 간단한 srt 자막 싱크 조절 코드

srt 파일의 싱크 조절이 필요해 간단하게 python으로 코드를 만들어 봤다. 테스트를 많이 해보진 못했지만, 싱크 조절하려 했던 파일들은 잘 동작하는 것을 확인했다. 

코드는 다음과 같다.

import os

def srt_gettimems(line,offset):
    while(line[offset].isdecimal() == False):
        offset += 1
        if line[offset] == '\r' or line[offset] == '\n':
            return 0
    hh = int(line[offset:offset+2])
    mm = int(line[offset+3:offset+5])
    sec = int(line[offset+6:offset+8])
    ms = int(line[offset+9:offset+12])
    return (hh*360+mm*60+sec)*1000+ms

def srt_conv2timestr(time_ms):
    ms = time_ms%1000
    time_sec = int(time_ms/1000)
    sec = time_sec%60
    mm = int(time_sec/60)
    hh = int(mm/60)
    mm = mm%60
    return '%02d:%02d:%02d,%03d'%(hh,mm,sec,ms)


def srt_modify_time(prev_line,line,modify_ms):
    pos = line.find('-->',0)
    if pos < 0 and prev_line.isdecimal() is not True:
        return None

    ms = srt_gettimems(line,0)
    ms += modify_ms
    modifyed_starttime = srt_conv2timestr(ms)
    
    ms = srt_gettimems(line,pos)
    ms += modify_ms
    modifyed_endtime = srt_conv2timestr(ms)
    
    return '%s --> %s\r\n'%(modifyed_starttime,modifyed_endtime)


def modify_srtsync(src_path,delay_ms):
    
    if os.path.isdir('modified') is False:
        os.mkdir('modified')
    
    with open(src_path,'rb') as fin:
        with open('modified/'+src_path,'wb') as fout:
            
            prev_line = ''
            while True:
                line = fin.readline()
                if len(line) <= 0:
                    break
                if line[0] == 0xef and line[1] == 0xbb and line[2] == 0xbf:
                    line = line[3:-1]
                
                new_time = srt_modify_time(prev_line,line.decode(),delay_ms)
                prev_line = line.decode()
                if new_time:
                    fout.write(new_time.encode())
                else:
                    fout.write(line)
            
            fout.flush()


if __name__ == "__main__":
        modify_srtsync('hello.srt',-5000)


modify_srtsync를 호출해 srt파일의 싱크를 조절하면 된다. 

def modify_srtsync(src_path,delay_ms):

src_path : srt 파일 위치.
delay_ms : 조절 하려는 시간. 밀리 세컨드 단위.


변환된 파일은 modified 폴더에 만들어진다.

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

base64 인코딩 디코딩 예제 c 소스

간단한 칼만 필터(Kalman Filter) 소스 코드와 사용 예제