Saltar al contenido

Empezando

  1. Instalar el paquete

    Ventana de terminal
    npm i @capgo/capacitor-ffmpeg
  2. Sincronización con proyectos nativos

    Ventana de terminal
    npx cap sync

Importe el complemento y utilícelo para volver a codificar 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);
};

Vuelva a codificar un archivo de vídeo con dimensiones y tasa de bits específicas.

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

Parámetros:

  • inputPath (cadena): ruta completa al archivo de vídeo de entrada
  • outputPath (cadena): Ruta completa donde se guardará el vídeo de salida
  • width (número): Ancho objetivo en píxeles
  • height (número): altura del objetivo en píxeles
  • bitrate (número, opcional): tasa de bits objetivo en bits por segundo

Obtenga la versión nativa del complemento 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. Utilice velocidades de bits apropiadas Elija la tasa de bits según la resolución y el caso de uso:

    // 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. Mantener la relación de aspecto Calcule las dimensiones para preservar la relación de aspecto:

    function calculateDimensions(originalWidth: number, originalHeight: number, targetWidth: number) {
    const aspectRatio = originalWidth / originalHeight;
    return {
    width: targetWidth,
    height: Math.round(targetWidth / aspectRatio)
    };
    }
  3. Maneje las rutas de los archivos correctamente Utilice el sistema de archivos Capacitor para el manejo de rutas multiplataforma:

    import { Filesystem, Directory } from '@capacitor/filesystem';
    const inputPath = await Filesystem.getUri({
    directory: Directory.Documents,
    path: 'input.mp4'
    });
  4. Mostrar el progreso a los usuarios El procesamiento de vídeo puede ser lento; informe a los usuarios:

    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. Limpiar archivos temporales Elimine archivos intermedios para ahorrar almacenamiento:

    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;
    }
  • Requiere iOS 11.0+
  • El procesamiento de videos de gran tamaño puede requerir permisos para tareas en segundo plano
  • Utiliza iOS VideoToolbox nativo para aceleración de hardware
  • Requiere Android 5.0 (API 21)+
  • La aceleración del hardware varía según el dispositivo.
  • Puede requerir permiso WRITE_EXTERNAL_STORAGE para acceder a archivos
  • No compatible con la plataforma web
  1. Resolución más baja para un procesamiento más rápido: Dimensiones más pequeñas = codificación más rápida
  2. Utilice aceleración de hardware: permita que la plataforma nativa optimice la codificación
  3. Proceso en segundo plano: no bloquee la interfaz de usuario durante el procesamiento del video
  4. Supervisar el uso de la memoria: los vídeos de gran tamaño pueden consumir una cantidad significativa de memoria
  5. Prueba en dispositivos reales: Es posible que los emuladores no reflejen el rendimiento real