跳转到内容

入门指南

  1. 安装包

    Terminal window
    npm i @capgo/capacitor-ffmpeg
  2. 与原生项目同步

    Terminal window
    npx cap sync

导入插件并使用它重新编码视频:

import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
// Re-encode a video with custom settings
const processVideo = async () => {
await CapacitorFFmpeg.reencodeVideo({
inputPath: '/path/to/input/video.mp4',
outputPath: '/path/to/output/video.mp4',
width: 1280,
height: 720,
bitrate: 2000000 // Optional: 2 Mbps
});
};
// Get plugin version
const checkVersion = async () => {
const { version } = await CapacitorFFmpeg.getPluginVersion();
console.log('FFmpeg plugin version:', version);
};

使用指定的尺寸和比特率重新编码视频文件。

await CapacitorFFmpeg.reencodeVideo({
inputPath: '/path/to/input.mp4',
outputPath: '/path/to/output.mp4',
width: 1920,
height: 1080,
bitrate: 5000000 // Optional: 5 Mbps
});

参数:

  • inputPath (string): 输入视频文件的完整路径
  • outputPath (string): 输出视频将保存的完整路径
  • width (number): 目标宽度(像素)
  • height (number): 目标高度(像素)
  • bitrate (number, 可选): 目标比特率(比特/秒)

获取原生 Capacitor 插件版本。

const { version } = await CapacitorFFmpeg.getPluginVersion();
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
import { Filesystem, Directory } from '@capacitor/filesystem';
export class VideoProcessor {
/**
* Compress a video to reduce file size
*/
async compressVideo(inputPath: string, quality: 'low' | 'medium' | 'high') {
const qualitySettings = {
low: { width: 640, height: 360, bitrate: 500000 },
medium: { width: 1280, height: 720, bitrate: 2000000 },
high: { width: 1920, height: 1080, bitrate: 5000000 }
};
const settings = qualitySettings[quality];
const outputPath = inputPath.replace('.mp4', `_${quality}.mp4`);
try {
await CapacitorFFmpeg.reencodeVideo({
inputPath,
outputPath,
width: settings.width,
height: settings.height,
bitrate: settings.bitrate
});
console.log(`Video compressed to ${quality} quality:`, outputPath);
return outputPath;
} catch (error) {
console.error('Video compression failed:', error);
throw error;
}
}
/**
* Resize video to specific dimensions
*/
async resizeVideo(
inputPath: string,
width: number,
height: number
): Promise<string> {
const outputPath = inputPath.replace('.mp4', '_resized.mp4');
await CapacitorFFmpeg.reencodeVideo({
inputPath,
outputPath,
width,
height
});
return outputPath;
}
/**
* Create a thumbnail-quality version of a video
*/
async createThumbnailVideo(inputPath: string): Promise<string> {
return this.compressVideo(inputPath, 'low');
}
/**
* Batch process multiple videos
*/
async processMultipleVideos(
videoPaths: string[],
width: number,
height: number,
bitrate?: number
): Promise<string[]> {
const outputPaths: string[] = [];
for (const inputPath of videoPaths) {
const outputPath = inputPath.replace('.mp4', '_processed.mp4');
try {
await CapacitorFFmpeg.reencodeVideo({
inputPath,
outputPath,
width,
height,
bitrate
});
outputPaths.push(outputPath);
} catch (error) {
console.error(`Failed to process ${inputPath}:`, error);
}
}
return outputPaths;
}
}
  1. 使用适当的比特率 根据分辨率和用例选择比特率:

    // Mobile sharing (low bandwidth)
    const lowQuality = { width: 640, height: 360, bitrate: 500000 };
    // Standard quality
    const standardQuality = { width: 1280, height: 720, bitrate: 2000000 };
    // High quality
    const highQuality = { width: 1920, height: 1080, bitrate: 5000000 };
  2. 保持纵横比 计算尺寸以保持纵横比:

    function calculateDimensions(originalWidth: number, originalHeight: number, targetWidth: number) {
    const aspectRatio = originalWidth / originalHeight;
    return {
    width: targetWidth,
    height: Math.round(targetWidth / aspectRatio)
    };
    }
  3. 正确处理文件路径 使用 Capacitor Filesystem 进行跨平台路径处理:

    import { Filesystem, Directory } from '@capacitor/filesystem';
    const inputPath = await Filesystem.getUri({
    directory: Directory.Documents,
    path: 'input.mp4'
    });
  4. 向用户显示进度 视频处理可能很慢 - 通知用户:

    async function processWithProgress(inputPath: string) {
    // Show loading indicator
    showLoading('Processing video...');
    try {
    await CapacitorFFmpeg.reencodeVideo({
    inputPath,
    outputPath: '/path/to/output.mp4',
    width: 1280,
    height: 720
    });
    showSuccess('Video processed successfully!');
    } catch (error) {
    showError('Failed to process video');
    } finally {
    hideLoading();
    }
    }
  5. 清理临时文件 删除中间文件以节省存储空间:

    async function processAndCleanup(inputPath: string) {
    const outputPath = inputPath.replace('.mp4', '_output.mp4');
    await CapacitorFFmpeg.reencodeVideo({
    inputPath,
    outputPath,
    width: 1280,
    height: 720
    });
    // Remove original if no longer needed
    await Filesystem.deleteFile({ path: inputPath });
    return outputPath;
    }
  • 需要 iOS 11.0+
  • 大型视频处理可能需要后台任务权限
  • 使用原生 iOS VideoToolbox 进行硬件加速
  • 需要 Android 5.0 (API 21)+
  • 硬件加速因设备而异
  • 可能需要 WRITE_EXTERNAL_STORAGE 权限才能访问文件
  • Web 平台不支持
  1. 降低分辨率以加快处理速度:较小的尺寸 = 更快的编码
  2. 使用硬件加速:让原生平台优化编码
  3. 在后台处理:视频处理期间不要阻塞 UI
  4. 监控内存使用:大型视频可能会消耗大量内存
  5. 在真实设备上测试:模拟器可能无法反映实际性能