Subtitles logo

Subtitles

Organization
MatrixReligio
subtitles

自动生成视频字幕。解析配音文案,生成同步字幕,使用 Remotion 组件渲染。支持中英文双语字幕。

Overview

PublisherMatrixReligio
RepositoryProductVideoCreator
Skill namesubtitles
Stars
44
Forks
9
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by MatrixReligio on GitHub. Read the source before you install it.

Installation

Install the Subtitles AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/MatrixReligio/ProductVideoCreator/tree/main/.claude/skills/subtitles
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/MatrixReligio/ProductVideoCreator.git /tmp/ProductVideoCreator
mkdir -p .claude/skills
cp -r /tmp/ProductVideoCreator/.claude/skills/subtitles .claude/skills/subtitles
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Subtitles in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Subtitles on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Subtitles is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

字幕自动生成技能

快速开始:使用模板

项目提供了可复用的字幕组件模板:

tsx
// 从模板导入
import { SubtitleDisplay, createSubtitlesFromMetadata } from "./components/SubtitleDisplay";
import type { Subtitle } from "./config/types";

模板位置:templates/components/SubtitleDisplay.tsx


重要:字幕时间同步

字幕时间必须基于 voiceover_metadata.json 的 actual_duration(实际时长),而非 target_duration(目标时长)。

tsx
// ✅ 正确:使用 actual_duration 计算 end 时间
const SUBTITLES: Subtitle[] = [
  {
    start: segment.start_time,
    end: segment.start_time + segment.actual_duration,  // 使用实际时长
    text: segment.text
  },
];

// ❌ 错误:使用 target_duration(可能导致字幕与音频不同步)
const SUBTITLES: Subtitle[] = [
  {
    start: segment.start_time,
    end: segment.start_time + segment.target_duration,  // 不要这样做
    text: segment.text
  },
];

验证字幕时间

tsx
import { validateSubtitleTiming } from "./components/SubtitleDisplay";

const { valid, warnings } = validateSubtitleTiming(SUBTITLES, VIDEO_DURATION);
if (!valid) {
  console.warn("字幕时间警告:", warnings);
}

工作流程

配音元数据 (voiceover_metadata.json)
        ↓
   解析文案和时间线
        ↓
   生成字幕数据 (subtitles.json)
        ↓
   Remotion 字幕组件渲染

字幕数据格式

输入:配音元数据

json
{
  "voice": "zh-CN-YunjianNeural",
  "total_duration": 85,
  "segments": [
    {
      "index": 0,
      "start_time": 0.5,
      "target_duration": 7.0,
      "actual_duration": 6.3,
      "text": "1993年,黄仁勋创立NVIDIA...",
      "language": "zh"
    }
  ]
}

输出:字幕数据

json
{
  "subtitles": [
    {
      "id": 0,
      "startFrame": 15,
      "endFrame": 204,
      "text": "1993年,黄仁勋创立NVIDIA",
      "language": "zh"
    }
  ],
  "fps": 30,
  "style": {
    "fontSize": 48,
    "fontFamily": "Noto Sans SC",
    "color": "#FFFFFF",
    "backgroundColor": "rgba(0, 0, 0, 0.7)",
    "position": "bottom"
  }
}

字幕生成脚本

python
#!/usr/bin/env python3
"""
字幕生成脚本 - 从配音元数据生成字幕
"""

import json
from pathlib import Path

FPS = 30
MAX_CHARS_PER_LINE = 20  # 中文每行最大字符数
MAX_WORDS_PER_LINE = 8   # 英文每行最大单词数

def split_text(text: str, language: str = "zh") -> list:
    """
    将长文本拆分成多行
    """
    if language == "zh":
        # 中文按字符拆分
        lines = []
        current_line = ""
        for char in text:
            if len(current_line) >= MAX_CHARS_PER_LINE:
                lines.append(current_line)
                current_line = char
            else:
                current_line += char
        if current_line:
            lines.append(current_line)
        return lines
    else:
        # 英文按单词拆分
        words = text.split()
        lines = []
        current_line = []
        for word in words:
            if len(current_line) >= MAX_WORDS_PER_LINE:
                lines.append(" ".join(current_line))
                current_line = [word]
            else:
                current_line.append(word)
        if current_line:
            lines.append(" ".join(current_line))
        return lines

def generate_subtitles(metadata_path: str, output_path: str):
    """
    从配音元数据生成字幕文件
    """
    with open(metadata_path, "r", encoding="utf-8") as f:
        metadata = json.load(f)

    subtitles = []
    subtitle_id = 0

    for segment in metadata["segments"]:
        text = segment.get("full_text", segment.get("text", ""))
        language = segment.get("language", "zh")
        start_time = segment["start_time"]
        duration = segment["actual_duration"]

        # 拆分长文本
        lines = split_text(text, language)

        # 计算每行显示时长
        line_duration = duration / len(lines) if lines else duration

        for i, line in enumerate(lines):
            line_start = start_time + i * line_duration
            line_end = line_start + line_duration

            subtitles.append({
                "id": subtitle_id,
                "startFrame": int(line_start * FPS),
                "endFrame": int(line_end * FPS),
                "text": line.strip(),
                "language": language
            })
            subtitle_id += 1

    output_data = {
        "subtitles": subtitles,
        "fps": FPS,
        "style": {
            "fontSize": 48,
            "fontFamily": "Noto Sans SC" if metadata["segments"][0].get("language") == "zh" else "Inter",
            "color": "#FFFFFF",
            "backgroundColor": "rgba(0, 0, 0, 0.7)",
            "position": "bottom",
            "padding": "12px 24px",
            "borderRadius": "8px"
        }
    }

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(output_data, f, ensure_ascii=False, indent=2)

    print(f"✓ 生成 {len(subtitles)} 条字幕")
    print(f"✓ 输出: {output_path}")

if __name__ == "__main__":
    generate_subtitles(
        metadata_path="public/audio/voiceover_metadata.json",
        output_path="public/subtitles.json"
    )

Remotion 字幕组件

SubtitleDisplay.tsx

tsx
import React from "react";
import { useCurrentFrame, interpolate, Easing } from "remotion";

interface Subtitle {
  id: number;
  startFrame: number;
  endFrame: number;
  text: string;
  language: string;
}

interface SubtitleStyle {
  fontSize: number;
  fontFamily: string;
  color: string;
  backgroundColor: string;
  position: "top" | "bottom" | "center";
  padding: string;
  borderRadius: string;
}

interface SubtitleDisplayProps {
  subtitles: Subtitle[];
  style: SubtitleStyle;
}

export const SubtitleDisplay: React.FC<SubtitleDisplayProps> = ({
  subtitles,
  style,
}) => {
  const frame = useCurrentFrame();

  // 找到当前帧应显示的字幕
  const currentSubtitle = subtitles.find(
    (sub) => frame >= sub.startFrame && frame < sub.endFrame
  );

  if (!currentSubtitle) return null;

  // 淡入淡出动画
  const fadeInDuration = 6; // 0.2秒
  const fadeOutDuration = 6;

  const opacity = interpolate(
    frame,
    [
      currentSubtitle.startFrame,
      currentSubtitle.startFrame + fadeInDuration,
      currentSubtitle.endFrame - fadeOutDuration,
      currentSubtitle.endFrame,
    ],
    [0, 1, 1, 0],
    {
      extrapolateLeft: "clamp",
      extrapolateRight: "clamp",
      easing: Easing.ease,
    }
  );

  // 位置样式
  const positionStyle: React.CSSProperties =
    style.position === "top"
      ? { top: 60 }
      : style.position === "center"
      ? { top: "50%", transform: "translateY(-50%)" }
      : { bottom: 80 };

  return (
    <div
      style={{
        position: "absolute",
        left: 0,
        right: 0,
        display: "flex",
        justifyContent: "center",
        ...positionStyle,
      }}
    >
      <div
        style={{
          opacity,
          fontSize: style.fontSize,
          fontFamily: style.fontFamily,
          color: style.color,
          backgroundColor: style.backgroundColor,
          padding: style.padding,
          borderRadius: style.borderRadius,
          textAlign: "center",
          maxWidth: "80%",
          lineHeight: 1.4,
          textShadow: "2px 2px 4px rgba(0,0,0,0.8)",
        }}
      >
        {currentSubtitle.text}
      </div>
    </div>
  );
};

集成到主视频

tsx
import React from "react";
import { Composition, staticFile } from "remotion";
import { SubtitleDisplay } from "./components/SubtitleDisplay";
import subtitleData from "../public/subtitles.json";

export const FinalVideo: React.FC = () => {
  return (
    <>
      {/* 其他视频内容 */}

      {/* 字幕层(最上层) */}
      <SubtitleDisplay
        subtitles={subtitleData.subtitles}
        style={subtitleData.style}
      />
    </>
  );
};

字幕样式配置

预设样式

风格fontSizefontFamily背景适用场景
默认48Noto Sans SCrgba(0,0,0,0.7)通用
科技42Interrgba(0,10,30,0.8)科技视频
简约44sans-seriftransparent简洁风格
强调56Noto Sans SC#76B900重点内容

双语字幕

tsx
// 双语字幕显示
interface BilingualSubtitle {
  primary: string;    // 主语言
  secondary: string;  // 次语言
}

export const BilingualSubtitleDisplay: React.FC<{
  subtitles: BilingualSubtitle[];
}> = ({ subtitles }) => {
  // ...
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontSize: 48, marginBottom: 8 }}>
        {currentSubtitle.primary}
      </div>
      <div style={{ fontSize: 32, opacity: 0.8 }}>
        {currentSubtitle.secondary}
      </div>
    </div>
  );
};

字幕位置调整

tsx
// 避免字幕遮挡重要内容
const getSubtitlePosition = (
  frame: number,
  scenes: Scene[]
): "top" | "bottom" => {
  const currentScene = scenes.find(
    (s) => frame >= s.startFrame && frame < s.endFrame
  );

  // 如果当前场景底部有重要内容,字幕显示在顶部
  if (currentScene?.hasBottomContent) {
    return "top";
  }
  return "bottom";
};

SRT 格式导出(可选)

python
def export_srt(subtitles: list, output_path: str, fps: int = 30):
    """导出 SRT 格式字幕文件"""
    def frame_to_timecode(frame: int) -> str:
        total_seconds = frame / fps
        hours = int(total_seconds // 3600)
        minutes = int((total_seconds % 3600) // 60)
        seconds = int(total_seconds % 60)
        milliseconds = int((total_seconds % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"

    with open(output_path, "w", encoding="utf-8") as f:
        for i, sub in enumerate(subtitles, 1):
            f.write(f"{i}\n")
            f.write(f"{frame_to_timecode(sub['startFrame'])} --> {frame_to_timecode(sub['endFrame'])}\n")
            f.write(f"{sub['text']}\n\n")

    print(f"✓ SRT 导出: {output_path}")

常见问题

问题解决方案
字幕闪烁增加 fadeInDuration/fadeOutDuration
字幕太长调整 MAX_CHARS_PER_LINE
字体不显示确保使用 @remotion/google-fonts 加载字体
字幕位置不对调整 position 和 bottom/top 值
字幕遮挡内容使用动态位置调整

Frequently asked questions

What does the Subtitles AI skill do?

自动生成视频字幕。解析配音文案,生成同步字幕,使用 Remotion 组件渲染。支持中英文双语字幕。

Why use Subtitles on TypingMind?

Because you install it once and use it with any model. Subtitles is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Subtitles in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/MatrixReligio/ProductVideoCreator/tree/main/.claude/skills/subtitles. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Subtitles?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Subtitles?

As many as you like. As long as a model supports skills, you can use Subtitles with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Subtitles AI skill free?

It is published on GitHub by MatrixReligio. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇