Passer au contenu

Getting Started

Ce contenu n'est pas encore disponible dans votre langue.

  1. Install the package

    Fenêtre de terminal
    npm i @capgo/capacitor-ffmpeg
  2. Sync with native projects

    Fenêtre de terminal
    npx cap sync

Usage

Import the plugin and use it to re-encode videos:

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);
};

API Reference

reencodeVideo(options)

Re-encode a video file with specified dimensions and bitrate.

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

Parameters:

  • inputPath (string): Full path to the input video file
  • outputPath (string): Full path where the output video will be saved
  • width (number): Target width in pixels
  • height (number): Target height in pixels
  • bitrate (number, optional): Target bitrate in bits per second

getPluginVersion()

Get the native Capacitor plugin version.

const { version } = await CapacitorFFmpeg.getPluginVersion();

Complete Example

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;
}
}

Best Practices

  1. Use appropriate bitrates Choose bitrate based on resolution and use case:

    // 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. Maintain aspect ratio Calculate dimensions to preserve aspect ratio:

    function calculateDimensions(originalWidth: number, originalHeight: number, targetWidth: number) {
    const aspectRatio = originalWidth / originalHeight;
    return {
    width: targetWidth,
    height: Math.round(targetWidth / aspectRatio)
    };
    }
  3. Handle file paths correctly Use Capacitor Filesystem for cross-platform path handling:

    import { Filesystem, Directory } from '@capacitor/filesystem';
    const inputPath = await Filesystem.getUri({
    directory: Directory.Documents,
    path: 'input.mp4'
    });
  4. Show progress to users Video processing can be slow - inform users:

    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. Clean up temporary files Remove intermediate files to save storage:

    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;
    }

Platform Notes

iOS

  • Requires iOS 11.0+
  • Large video processing may require background task permissions
  • Uses native iOS VideoToolbox for hardware acceleration

Android

  • Requires Android 5.0 (API 21)+
  • Hardware acceleration varies by device
  • May require WRITE_EXTERNAL_STORAGE permission for file access

Web

  • Not supported on web platform

Performance Tips

  1. Lower resolution for faster processing: Smaller dimensions = faster encoding
  2. Use hardware acceleration: Let the native platform optimize encoding
  3. Process in background: Don’t block UI during video processing
  4. Monitor memory usage: Large videos can consume significant memory
  5. Test on real devices: Emulators may not reflect actual performance