# @happyvertical/video 中文文档

规范地址：https://npmcn.com/package/%40happyvertical/video/

版本：0\.113\.1
npm 元数据更新时间：2026-11-17T00:03:51.170Z
中文译文更新时间：2026-11-17T14:18:13.765Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40happyvertical/video
原文对照：https://npmcn.com/package/%40happyvertical/video/?lang=original
项目主页：https://github.com/happyvertical/sdk/tree/main/packages/video#readme
源码仓库：https://github.com/happyvertical/sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：140 kB，8 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2026-06-23T08:14:21.742Z
- 最新版本发布：2026-11-17T00:03:50.999Z
- 近 30 天下载量：5425（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：131（近 12 个月 131 个）

## 中文简介

具有适配器构成和转码模式的视频处理工具

## 安装

```sh
npm install @happyvertical/video
```

也可以使用：`pnpm add @happyvertical/video`、`yarn add @happyvertical/video`、`bun add @happyvertical/video`

## README

* * *

## 编号:视频 标题:"@happyvertical/video:视频处理" 侧边栏 标签: "@ happyvertical/video" 侧边栏( p): 12

# @ 快乐的垂直/视频

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

在HARE SDK中具有可适配器模式的视频处理功能,用于组成和转码.

## 概览

这个 `@happyvertical/video` 软件包为使用FFmpeg的视频处理操作提供统一接口. 它支持视频组成,转码,上线布置,缩略图提取,以及下第三代用于新闻风格的视频制作.

## 特征

-   **视频组成**: 合并视频、音频和覆盖
-   **转码**: 在格式之间转换并调整质量
-   **缩略图提取**: 在特定时间戳上提取帧
-   **下三级重叠**: 新闻风格名称/标题图形
-   **图像重叠**: 位置标志和水印
-   **音频混合**: 合并多个音频音轨
-   **元数据提取**: 获取持续时间、 分辨率、 编码信息
-   **格式转换**: 支持 MP4, WebM, MOV 等
-   **类型安全**: 完整类型脚本支持

## 安装

```bash
# Install with bun (recommended)
bun add @happyvertical/video

# Or with npm
npm install @happyvertical/video

# Or with pnpm
pnpm add @happyvertical/video
```

### 先决条件

FFmpeg 必须在您的系统中安装和提供 PATH :

```bash
# macOS
brew install ffmpeg

# Ubuntu/Debian
sudo apt install ffmpeg

# Windows (with Chocolatey)
choco install ffmpeg
```

## 快速启动

### 基本用途

```typescript
import { FFmpegProcessor } from '@happyvertical/video';

const processor = new FFmpegProcessor();

// Get video metadata
const metadata = await processor.getMetadata('input.mp4');
console.log(`Duration: ${metadata.duration}s`);
console.log(`Resolution: ${metadata.width}x${metadata.height}`);
console.log(`FPS: ${metadata.fps}`);

// Extract thumbnail
const thumbnail = await processor.extractFrame('input.mp4', 2.0, {
  format: 'jpg',
  width: 1280,
  quality: 90,
});
fs.writeFileSync('thumbnail.jpg', thumbnail);
```

### 视频组成

```typescript
const output = await processor.compose({
  baseVideo: 'input.mp4',
  audio: 'narration.mp3',
  overlays: [
    {
      type: 'image',
      content: 'logo.png',
      position: { x: 'right', y: 'top', padding: 20 },
      opacity: 0.8,
    },
    {
      type: 'text',
      content: 'BREAKING NEWS',
      position: { x: 'center', y: 'bottom', padding: 50 },
      style: {
        fontSize: 48,
        fontColor: 'white',
        backgroundColor: 'red',
      },
    },
  ],
  outputFormat: 'mp4',
  quality: 20,
});

fs.writeFileSync('output.mp4', output);
```

### 下三层图形

```typescript
// Add news-style lower-third with name and title
const output = await processor.addLowerThird('input.mp4', {
  title: 'John Smith',
  subtitle: 'Senior Correspondent',
  style: 'news',
  primaryColor: '#1a1a1a',
  accentColor: '#cc0000',
  duration: 5, // seconds
  startTime: 0,
  fadeIn: 0.5,
  fadeOut: 0.5,
});
```

### 社会平台转码

```typescript
// YouTube Shorts (9:16 vertical)
const youtubeShort = await processor.transcode('input.mp4', {
  format: 'mp4',
  width: 1080,
  height: 1920,
  video: {
    codec: 'h264',
    preset: 'medium',
    crf: 23,
  },
  audio: {
    codec: 'aac',
    bitrate: '128k',
  },
});

// Web-optimized (16:9 horizontal)
const webVideo = await processor.transcode('input.mp4', {
  format: 'mp4',
  width: 1920,
  height: 1080,
  video: {
    codec: 'h264',
    preset: 'slow',
    crf: 20,
  },
  audio: {
    codec: 'aac',
    bitrate: '192k',
  },
});
```

## API 参考

### FFmpeg 处理器

视频业务的主要处理器类.

#### 构造器

```typescript
new FFmpegProcessor(options?: VideoProcessorOptions)
```

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `ffmpegPath` | `string` | `'ffmpeg'` | FFmpeg 二进制路径 |
| `ffprobePath` | `string` | `'ffprobe'` | FF Probe 二进制路径 |
| `tempDir` | `string` | 系统临时 | 临时文件目录 |
| `timeout` | `number` | `300000` | 处理超时( 毫秒) |

#### 方法

##### 获取元数据

获取视频文件元数据 .

```typescript
async getMetadata(video: Buffer | string): Promise<VideoMetadata>
```

##### 节选Frame

取出一帧为图像.

```typescript
async extractFrame(
  video: Buffer | string,
  timestamp: number,
  options?: ExtractFrameOptions
): Promise<Buffer>
```

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `format` | `'jpg' | 'png' | 'webp'` | `'jpg'` | 输出格式 |
| `width` | `number` | 原文 | 输出宽度 |
| `height` | `number` | 原文 | 输出高度 |
| `quality` | `number` | `85` | JPEG 质量(1-100) |

##### 编曲

以覆盖和音频来作曲视频.

```typescript
async compose(options: ComposeOptions): Promise<Buffer>
```

##### 添加倒数第三

添加下第三图形覆盖.

```typescript
async addLowerThird(
  video: Buffer | string,
  config: LowerThirdConfig
): Promise<Buffer>
```

##### 转码

转换视频格式并调整质量.

```typescript
async transcode(
  video: Buffer | string,
  options: TranscodeOptions
): Promise<Buffer>
```

##### 添加重叠

将图像或文本覆盖到视频中 .

```typescript
async addOverlay(
  video: Buffer | string,
  overlay: OverlayConfig
): Promise<Buffer>
```

### 类型

```typescript
interface VideoMetadata {
  duration: number; // seconds
  width: number;
  height: number;
  fps: number;
  codec: string;
  bitrate?: number;
  audioCodec?: string;
  audioBitrate?: number;
  audioSampleRate?: number;
}

interface ComposeOptions {
  baseVideo: Buffer | string;
  audio?: Buffer | string;
  overlays?: OverlayConfig[];
  outputFormat?: VideoFormat;
  quality?: number; // CRF value (lower = better)
}

interface OverlayConfig {
  type: 'image' | 'text';
  content: Buffer | string;
  position: OverlayPosition;
  opacity?: number; // 0-1
  startTime?: number;
  duration?: number;
  fadeIn?: number;
  fadeOut?: number;
  style?: TextOverlayOptions;
}

interface OverlayPosition {
  x: number | 'left' | 'center' | 'right';
  y: number | 'top' | 'center' | 'bottom';
  padding?: number;
}

interface LowerThirdConfig {
  title: string;
  subtitle?: string;
  style?: 'news' | 'minimal' | 'modern';
  primaryColor?: string;
  accentColor?: string;
  textColor?: string;
  duration?: number;
  startTime?: number;
  fadeIn?: number;
  fadeOut?: number;
}

interface TranscodeOptions {
  format: VideoFormat;
  width?: number;
  height?: number;
  video?: VideoCodecOptions;
  audio?: AudioCodecOptions;
}

interface VideoCodecOptions {
  codec: 'h264' | 'h265' | 'vp9' | 'av1';
  preset?: 'ultrafast' | 'fast' | 'medium' | 'slow' | 'veryslow';
  crf?: number; // 0-51 (lower = better quality)
  bitrate?: string; // e.g., '5M'
}

interface AudioCodecOptions {
  codec: 'aac' | 'mp3' | 'opus';
  bitrate?: string; // e.g., '128k'
  sampleRate?: number; // e.g., 48000
}

type VideoFormat = 'mp4' | 'webm' | 'mov' | 'avi' | 'mkv';
```

## 使用大小写

### 新闻录像制作管道

```typescript
import { FFmpegProcessor } from '@happyvertical/video';

async function processNewsVideo(rawVideo: string, anchorName: string) {
  const processor = new FFmpegProcessor();

  // 1. Add lower-third with anchor name
  const withLowerThird = await processor.addLowerThird(rawVideo, {
    title: anchorName,
    subtitle: 'News Correspondent',
    style: 'news',
    primaryColor: '#1a237e',
    accentColor: '#c62828',
    duration: 5,
    startTime: 0,
  });

  // 2. Add station logo
  const withLogo = await processor.addOverlay(withLowerThird, {
    type: 'image',
    content: 'station-logo.png',
    position: { x: 'right', y: 'top', padding: 20 },
    opacity: 0.9,
  });

  // 3. Create multiple formats for distribution
  const youtubeShort = await processor.transcode(withLogo, {
    format: 'mp4',
    width: 1080,
    height: 1920,
    video: { codec: 'h264', preset: 'medium', crf: 23 },
  });

  const webVersion = await processor.transcode(withLogo, {
    format: 'mp4',
    width: 1920,
    height: 1080,
    video: { codec: 'h264', preset: 'medium', crf: 20 },
  });

  // 4. Extract thumbnail
  const thumbnail = await processor.extractFrame(withLogo, 2.0, {
    format: 'jpg',
    width: 1280,
    quality: 90,
  });

  return { youtubeShort, webVersion, thumbnail };
}
```

### 批量缩略图生成

```typescript
async function generateThumbnails(videos: string[], timestamps: number[] = [2.0]) {
  const processor = new FFmpegProcessor();
  const thumbnails = [];

  for (const video of videos) {
    for (const timestamp of timestamps) {
      const thumbnail = await processor.extractFrame(video, timestamp, {
        format: 'webp',
        width: 1280,
        quality: 85,
      });
      thumbnails.push({
        video,
        timestamp,
        data: thumbnail,
      });
    }
  }

  return thumbnails;
}
```

## 最佳做法

### 内存管理

```typescript
// For large videos, use file paths instead of buffers
const output = await processor.transcode('/path/to/large-video.mp4', {
  format: 'mp4',
  // ...options
});

// Write output to file instead of keeping in memory
fs.writeFileSync('/path/to/output.mp4', output);
```

### 质量与大小权衡

```typescript
// High quality (larger file)
{ video: { codec: 'h264', preset: 'slow', crf: 18 } }

// Balanced (recommended)
{ video: { codec: 'h264', preset: 'medium', crf: 23 } }

// Fast encoding (lower quality)
{ video: { codec: 'h264', preset: 'fast', crf: 28 } }
```

### 平台特定编码

```typescript
// YouTube recommended settings
{
  format: 'mp4',
  video: { codec: 'h264', preset: 'slow', crf: 18 },
  audio: { codec: 'aac', bitrate: '384k' },
}

// Twitter/X recommended settings
{
  format: 'mp4',
  video: { codec: 'h264', preset: 'medium', crf: 23 },
  audio: { codec: 'aac', bitrate: '128k' },
}
```

## 许可证

这个包是HE SDK的一部分,根据麻省理工学院的许可证获得许可——见 [自由主义](https://npmcn.com/package/LICENSE) 详细文件.

## 常见问题

### @happyvertical/video 是什么？

具有适配器构成和转码模式的视频处理工具

### 如何安装 @happyvertical/video？

在项目目录运行 npm install @happyvertical/video，或使用 pnpm add / yarn add / bun add。

### @happyvertical/video 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @happyvertical/video 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @happyvertical/video 可以商用吗？

@happyvertical/video 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @happyvertical/video 的下载量有多少？

根据 npm 官方下载统计，@happyvertical/video 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,425 次，日均约 181 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @happyvertical/video 还在维护吗？

最新版本 0\.113\.1 发布于 2026/11/17（今天）；至今共发布 131 个版本，其中过去 12 个月发布了 131 个；首次发布于 2026/06/23。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

