Communitygithub.com

AI 短视频生成器 — 短内容流水线

使用 AI 自动化创建短视频(TikTok、YouTube Shorts、Instagram Reels),涵盖脚本撰写、文字转语音、素材选择、字幕生成和视频合成。

AI 短视频生成器 — 短内容流水线 是什么?

该技能是一个完整的短视频生成流水线,专为创建适用于 TikTok、YouTube Shorts 和 Instagram Reels 的短内容而设计。它利用 AI 完成每个步骤:首先使用 Anthropic 或 OpenAI 模型根据主题和时长自动编写脚本,然后通过 ElevenLabs 或 OpenAI TTS 生成自然语音旁白。接着,它从 Pexels 搜索纵向方向的免版税素材,并使用 WhisperX 精准为音频生成词级字幕。最后,通过 FFmpeg 将所有元素组装成 1080x1920 的纵向视频,包含字幕叠加和音频同步。此技能对于希望自动化内容生产流水线,同时保持高质量和低成本(每段视频约 $0.05-$0.10)的创作者特别有用。

兼容平台✓Claude Code✓Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/ai-video-generator

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

AI 视频生成器 — 短内容流水线

概述

使用 AI 自动化创建短视频(TikTok、YouTube Shorts、Instagram Reels)的每个步骤:话题研究、脚本撰写、文字转语音旁白、素材匹配、字幕生成和最终合成。灵感来自 MoneyPrinterTurbo(53k+ 星)。

说明

步骤 1:设置环境

pip install anthropic openai requests moviepy pydub whisperx srt
sudo apt install ffmpeg  # Linux — 或:brew install ffmpeg (macOS)

需要的 API 密钥: Anthropic 或 OpenAI(脚本)、ElevenLabs 或 OpenAI TTS(语音)、Pexels(免费素材)。

步骤 2:AI 脚本撰写

import anthropic

def generate_script(topic, duration_seconds=45):
    """为短内容生成优化的视频脚本。"""
    client = anthropic.Anthropic()
    prompt = f"""写一段 {duration_seconds} 秒的视频脚本,主题:{topic}
    格式:
    钩子(前 3 秒):令人震惊的陈述或问题,让观众停止滑动
    主体(主要内容):3-5 个有力的事实或要点,每个 1-2 句话
    行动号召(最后 5 秒):关注、点赞、评论
    规则:
    - 口语化,不使用复杂句子
    - 每句话单独一行
    - 约 {duration_seconds * 2.5:.0f} 字({duration_seconds}s,语速 150wpm)
    - 使用强力词汇:秘密、震惊、没人告诉你、实际上
    - 无表情符号或话题标签——这是旁白脚本
    """
    response = client.messages.create(
        model="claude-sonnet-4-20250514", max_tokens=500,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

步骤 3:文字转语音旁白

import requests, os

def generate_voice_elevenlabs(text, output_path='narration.mp3'):
    """使用 ElevenLabs 生成旁白。"""
    url = "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"
    headers = {"xi-api-key": os.environ["ELEVENLABS_API_KEY"], "Content-Type": "application/json"}
    data = {"text": text, "model_id": "eleven_turbo_v2_5",
            "voice_settings": {"stability": 0.5, "similarity_boost": 0.75}}
    response = requests.post(url, json=data, headers=headers)
    with open(output_path, 'wb') as f:
        f.write(response.content)
    return output_path

def generate_voice_openai(text, output_path='narration.mp3'):
    """使用 OpenAI TTS 生成旁白(更便宜的选择)。"""
    from openai import OpenAI
    client = OpenAI()
    response = client.audio.speech.create(model="tts-1-hd", voice="onyx", input=text)
    response.stream_to_file(output_path)
    return output_path

步骤 4:素材选择

def search_pexels_videos(query, count=5):
    """在 Pexels 搜索纵向方向的免版税视频片段。"""
    url = "https://api.pexels.com/videos/search"
    headers = {"Authorization": os.environ["PEXELS_API_KEY"]}
    params = {"query": query, "per_page": count, "orientation": "portrait", "size": "medium"}
    response = requests.get(url, headers=headers, params=params)
    videos = response.json().get('videos', [])
    results = []
    for v in videos:
        files = sorted(v['video_files'], key=lambda x: x.get('height', 0), reverse=True)
        hd = next((f for f in files if f.get('height', 0) >= 720), files[0])
        results.append({'id': v['id'], 'url': hd['link'], 'duration': v['duration']})
    return results

步骤 5:字幕生成

def generate_subtitles(audio_path, output_srt='subtitles.srt'):
    """使用 WhisperX 生成词级字幕。"""
    import whisperx, srt
    from datetime import timedelta
    model = whisperx.load_model("base", device="cpu")
    audio = whisperx.load_audio(audio_path)
    result = model.transcribe(audio)
    align_model, metadata = whisperx.load_align_model(language_code="en")
    aligned = whisperx.align(result["segments"], align_model, metadata, audio)
    subs = []
    words = [w for seg in aligned["segments"] for w in seg.get("words", [])]
    for i in range(0, len(words), 4):
        group = words[i:i + 4]
        if not group: continue
        start = timedelta(seconds=group[0].get('start', 0))
        end = timedelta(seconds=group[-1].get('end', 0))
        text = ' '.join(w['word'] for w in group)
        subs.append(srt.Subtitle(index=len(subs)+1, start=start, end=end, content=text))
    with open(output_srt, 'w') as f:
        f.write(srt.compose(subs))
    return output_srt

步骤 6:使用 FFmpeg 合成视频

import subprocess

def assemble_video(clips, narration, subtitles, output='final.mp4'):
    """合成最终视频:拼接片段、添加旁白和字幕。"""
    concat_list = 'concat_list.txt'
    with open(concat_list, 'w') as f:
        for clip in clips:
            f.write(f"file '{clip}'\n")
    subprocess.run([
        'ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list,
        '-vf', 'scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920',
        '-c:v', 'libx264', '-preset', 'fast', '-an', 'temp_video.mp4'
    ], check=True)
    subtitle_filter = (f"subtitles={subtitles}:force_style='"
        "FontName=Arial,FontSize=18,PrimaryColour=&H00FFFFFF,"
        "OutlineColour=&H00000000,Outline=2,Bold=1,Alignment=2'")
    subprocess.run([
        'ffmpeg', '-y', '-i', 'temp_video.mp4', '-i', narration,
        '-vf', subtitle_filter, '-c:v', 'libx264', '-c:a', 'aac',
        '-shortest', output
    ], check=True)
    return output

步骤 7:完整流水线

def generate_video(topic, output_dir='./output'):
    """完整流水线:主题 -> 完成视频。"""
    import os
    os.makedirs(output_dir, exist_ok=True)
    script = generate_script(topic)
    narration = generate_voice_elevenlabs(script, f'{output_dir}/narration.mp3')
    keywords = topic.split()[:3]
    videos = search_pexels_videos(' '.join(keywords), count=3)
    clips = []
    for i, v in enumerate(videos):
        path = f'{output_dir}/clip_{i}.mp4'
        requests.get(v['url'], stream=True)  # 下载片段
        clips.append(path)
    subs = generate_subtitles(narration, f'{output_dir}/subs.srt')
    return assemble_video(clips, narration, subs, f'{output_dir}/final.mp4')

示例

示例 1:批量生成科技事实短视频

一位创作者一次性为 TikTok 生成 5 个科技主题短视频:

topics = [
    "没人谈论的 AI 工具",
    "感觉像非法免费使用的应用",
    "让你大开眼界的网站",
    "每个学生都需要的免费 AI 工具",
    "改变我生活的 50 美元以下科技小工具"
]
for topic in topics:
    output = generate_video(topic, output_dir=f'./output/{topic[:30]}')
    print(f"视频已就绪:{output}")
# 每个视频:约 45 秒,纵向 1080x1920,带字幕和旁白
# 总成本:约 $0.25(5 x $0.05 每个视频)使用 ElevenLabs + Claude Sonnet

示例 2:每日财经 Shorts 用于 YouTube

一个财经频道自动化每日 Shorts 上传,使用热门财经话题:

import schedule

def daily_finance_video():
    topic = "三个真正有效的 2025 年被动收入点子"
    script = generate_script(topic, duration_seconds=55)
    # 脚本输出:
    # 钩子:"你每天都在亏钱,因为你不知道这些。"
    # 主体:1. 按需印刷商店($500-2k/月)
    #       2. AI 生成内容授权($300-1k/月)
    #       3. 股息 ETF 堆叠($200-800/月被动收入)
    # 行动号召:"关注我,获取没人告诉你的理财技巧。"
    narration = generate_voice_openai(script, './daily/narration.mp3')
    videos = search_pexels_videos("money finance investing", count=4)
    # 下载 4 个钱币/图表/生活方式纵向片段
    # 用粗体白色字幕合成,输出 55 秒 Short
    final = assemble_video(['./daily/clip_0.mp4', './daily/clip_1.mp4'],
                           narration, './daily/subs.srt', './daily/final.mp4')

schedule.every().day.at("08:00").do(daily_finance_video)

指导方针

  • 尊重版权 — 仅使用免版税素材(Pexels、Pixabay)或你自己的内容
  • 公开 AI 使用 — YouTube 和 TikTok 要求公开 AI 生成内容
  • 发布前检查 — 始终观看最终视频;AI 脚本可能包含不准确信息
  • 优化前 3 秒 — 钩子决定观众是停留还是滑动
  • 测试多种语音 — ElevenLabs 提供数十种语音;找到适合你领域的声音
  • 监控表现 — 跟踪观看次数、留存率和点击率,以迭代内容风格

参考

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

TerminalSkills/skills

>- Lovable (formerly GPT Engineer) is a browser-based AI app builder that turns a natural-language description into a working full-stack web app with a built-in backend, authentication, database and one-click publishing. Use when the user wants to prototype or ship a web app with Lovable, write effective Lovable prompts, connect Supabase or GitHub, review generated security rules, or move a Lovable project into their own editor.

相关技能