python srt字幕与视频合并

字幕文件读取

# 读取字幕文件
def read_srt(path):
    content = ""
    with open(path,'r', encoding='UTF-8') as f:
        content = f.read()
        return content

# 字幕拆分
def get_sequences(content):
    sequences = content.split('\n\n')
    sequences = [sequence.split('\n') for sequence in sequences]
    # 去除每一句空值
    sequences = [list(filter(None, sequence)) for sequence in sequences]
    # 去除整体空值
    return list(filter(None, sequences))

srt_path='./audio/333.zh-cn.srt'
content = read_srt(srt_path)
sequences = get_sequences(content)
print(sequences)

在这里插入图片描述

结果:
[[‘1’, ‘00:00:00,000 --> 00:00:00,790’, ‘活着’],
[‘2’, ‘00:00:01,730 --> 00:00:02,860’, ‘所为何事先生’],
[‘3’, ‘00:00:03,140 --> 00:00:05,010’, ‘我们在京城有一箱22任务’],
[‘4’, ‘00:00:05,230 --> 00:00:06,440’, ‘把这些人找过来’],
[‘5’, ‘00:00:07,010 --> 00:00:08,230’, ‘你就要辛苦一下了’], [‘6’, ‘00:00:09,290 --> 00:00:10,900’, ‘这一次我们要一起合作’], [‘7’, ‘00:00:11,020 --> 00:00:12,040’, ‘有目标是谁’],。。。

转换时间

strTime= '00:00:58,990'

def strFloatTime(tempStr):
    xx = tempStr.split(':')
    hour = int(xx[0])
    minute = int(xx[1])
    second = int(xx[2].split(',')[0])
    minsecond = int(xx[2].split(',')[1])
    allTime = hour * 60 * 60 + minute * 60 + second + minsecond / 1000
    return allTime
print(strFloatTime(strTime))

结果:58.99

字幕挂载

from os.path import splitext, isfile

from moviepy.editor import (VideoFileClip,
                            TextClip,
                            CompositeVideoClip)


# 读取字幕文件
def read_srt(path):
    content = ""
    with open(path, 'r', encoding='UTF-8') as f:
        content = f.read()
        return content


# 字幕拆分
def get_sequences(content):
    sequences = content.split('\n\n')
    sequences = [sequence.split('\n') for sequence in sequences]
    # 去除每一句空值
    sequences = [list(filter(None, sequence)) for sequence in sequences]
    # 去除整体空值
    return list(filter(None, sequences))


def strFloatTime(tempStr):
    xx = tempStr.split(':')
    hour = int(xx[0])
    minute = int(xx[1])
    second = int(xx[2].split(',')[0])
    minsecond = int(xx[2].split(',')[1])
    allTime = hour * 60 * 60 + minute * 60 + second + minsecond / 1000
    return allTime

class RealizeAddSubtitles():
    '''
    合成字幕与视频
    '''

    def __init__(self, videoFile, txtFile):
        self.src_video = videoFile
        self.sentences = txtFile
        if not (isfile(self.src_video) and self.src_video.endswith(('.avi', '.mp4')) and isfile(
                self.sentences) and self.sentences.endswith('.srt')):
            print('视频仅支持avi以及mp4,字幕仅支持srt格式')
        else:
            video = VideoFileClip(self.src_video)
            # 获取视频的宽度和高度
            w, h = video.w, video.h
            # 所有字幕剪辑
            txts = []
            content = read_srt(self.sentences)
            sequences = get_sequences(content)

            for line in sequences:
                if len(line)<3:
                    continue
                sentences = line[2]
                start = line[1].split(' --> ')[0]
                end = line[1].split(' --> ')[1]

                start=strFloatTime(start)
                end=strFloatTime(end)

                start, end = map(float, (start, end))
                span=end-start
                txt = (TextClip(sentences, fontsize=40,
                                font='SimHei', size=(w - 20, 40),
                                align='center', color='red')
                       .set_position((10, h - 150))
                       .set_duration(span)
                       .set_start(start))

                txts.append(txt)
            # 合成视频,写入文件
            video = CompositeVideoClip([video, *txts])
            fn, ext = splitext(self.src_video)
            video.write_videofile(f'{fn}_2带字幕{ext}')


if __name__ == '__main__':
    '''调用方法示例'''
    srt_path = './audio/333.zh-cn.srt'
    addSubtitles = RealizeAddSubtitles('./audio/clip.mp4', srt_path)

在这里插入图片描述

参考网页

  1. https://blog.csdn.net/weixin_42081389/article/details/104322629
  2. https://www.mdeditor.tw/pl/p7Q8
  3. https://blog.csdn.net/weixin_46304253/article/details/109157104
  4. https://blog.csdn.net/jining11/article/details/108016151
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值