跳转至

VHS 终端录制

为什么要学 VHS

VHS 是一个终端录制工具,用 Go 编写,由 Charm 团队开发。它通过编写简单的 .tape 脚本文件来定义终端操作序列,然后自动执行并录制为 GIF、MP4 或 WebM 格式。与 asciinema 等工具不同,VHS 的录制完全可编程和可复现,非常适合为 README、文档和教程生成高质量的终端演示动画。


核心概念

概念白话解释用途
Tape录制脚本定义要执行的终端操作
Type输入模拟键盘输入
Sleep等待控制操作间的停顿
Set设置配置终端外观
Output输出指定录制格式和路径

安装配置

# macOS
brew install vhs

# Go
go install github.com/charmbracelet/vhs@latest

# 需要 ttyd 和 ffmpeg
brew install ttyd ffmpeg  # macOS
sudo apt install ttyd ffmpeg  # Ubuntu

快速上手

创建 Tape 文件

# demo.tape
Output demo.gif

Set FontSize 14
Set Width 800
Set Height 400
Set Theme "Catppuccin Mocha"

Type "echo 'Hello, VHS!'"
Sleep 500ms
Enter
Sleep 1s

Type "ls -la"
Sleep 500ms
Enter
Sleep 2s

Type "echo 'Done!'"
Enter
Sleep 1s

执行录制

vhs demo.tape
# 生成 demo.gif

常用命令

# 输入
Type "command"           # 逐字输入
Type@100ms "fast input"  # 指定输入速度

# 按键
Enter                    # 回车
Backspace               # 退格
Tab                     # Tab
Space                   # 空格
Up/Down/Left/Right      # 方向键
Ctrl+C                  # Ctrl 组合键
Escape                  # ESC

# 等待
Sleep 1s                # 等待1秒
Sleep 500ms             # 等待500毫秒

# 设置
Set FontSize 16
Set Width 1200
Set Height 600
Set Padding 20
Set Theme "Dracula"
Set Shell "zsh"

# 输出格式
Output demo.gif
Output demo.mp4
Output demo.webm

进阶用法

完整项目演示

# project-demo.tape
Output project_demo.gif

Set FontSize 13
Set Width 1000
Set Height 600
Set Theme "GitHub Dark"
Set TypingSpeed 50ms

# 展示项目结构
Type "tree -L 2"
Enter
Sleep 2s

# 运行测试
Type "pytest tests/ -v"
Enter
Sleep 3s

# 启动服务
Type "python -m uvicorn main:app --reload"
Enter
Sleep 2s

# 测试 API
Type "curl localhost:8000/health"
Enter
Sleep 1s

Ctrl+C
Sleep 500ms

Type "echo '演示完成 ✓'"
Enter
Sleep 1s

主题和样式

# 可用主题
Set Theme "Catppuccin Mocha"
Set Theme "Dracula"
Set Theme "GitHub Dark"
Set Theme "One Dark"
Set Theme "Tokyo Night"

# 自定义外观
Set FontFamily "JetBrainsMono Nerd Font"
Set FontSize 14
Set LineHeight 1.2
Set Padding 20
Set Margin 10
Set MarginFill "#1e1e2e"
Set BorderRadius 8
Set WindowBar "Colorful"       # 窗口按钮样式
Set CursorBlink true

隐藏命令输出

# 执行但不录制
Hide
Type "clear"
Enter
Show

# 等待命令完成
Type "npm install"
Enter
Sleep 10s  # 等待安装完成

验证 Tape 语法

# 检查语法但不执行
vhs validate demo.tape

# 从已有录制生成 tape
vhs record > recorded.tape

常见问题

Q: GIF 文件太大?

Set Framerate 10        # 降低帧率(默认50)
Set Width 600           # 减小尺寸
或后处理:gifsicle -O3 --lossy=80 demo.gif -o demo_small.gif

Q: 与 asciinema 相比?

  • VHS:脚本化、可复现、输出 GIF/MP4
  • asciinema:录制真实操作、在线播放器、无法导出视频

Q: 中文显示问题?

设置支持中文的字体:Set FontFamily "Noto Sans Mono CJK SC"


参考资源

  • GitHub:https://github.com/charmbracelet/vhs
  • 命令参考:https://github.com/charmbracelet/vhs#vhs-command-reference
  • 主题列表:https://github.com/charmbracelet/vhs#themes
  • 示例:https://github.com/charmbracelet/vhs/tree/main/examples