Memulai
-
Instal paket
Terminal window npm i @capgo/capacitor-ffmpegTerminal window pnpm add @capgo/capacitor-ffmpegTerminal window yarn add @capgo/capacitor-ffmpegTerminal window bun add @capgo/capacitor-ffmpeg -
Sinkronkan dengan proyek native
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
Penggunaan
Section titled “Penggunaan”Import plugin dan gunakan untuk meng-encode ulang video:
import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
// Re-encode a video with custom settingsconst 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 versionconst checkVersion = async () => { const { version } = await CapacitorFFmpeg.getPluginVersion(); console.log('FFmpeg plugin version:', version);};Referensi API
Section titled “Referensi API”reencodeVideo(options)
Section titled “reencodeVideo(options)”Encode ulang file video dengan dimensi dan bitrate yang ditentukan.
await CapacitorFFmpeg.reencodeVideo({ inputPath: '/path/to/input.mp4', outputPath: '/path/to/output.mp4', width: 1920, height: 1080, bitrate: 5000000 // Optional: 5 Mbps});Parameter:
inputPath(string): Path lengkap ke file video inputoutputPath(string): Path lengkap di mana video output akan disimpanwidth(number): Lebar target dalam pixelheight(number): Tinggi target dalam pixelbitrate(number, opsional): Bitrate target dalam bit per detik
getPluginVersion()
Section titled “getPluginVersion()”Dapatkan versi plugin Capacitor native.
const { version } = await CapacitorFFmpeg.getPluginVersion();Contoh Lengkap
Section titled “Contoh Lengkap”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; }}Praktik Terbaik
Section titled “Praktik Terbaik”-
Gunakan bitrate yang sesuai Pilih bitrate berdasarkan resolusi dan use case:
// Mobile sharing (low bandwidth)const lowQuality = { width: 640, height: 360, bitrate: 500000 };// Standard qualityconst standardQuality = { width: 1280, height: 720, bitrate: 2000000 };// High qualityconst highQuality = { width: 1920, height: 1080, bitrate: 5000000 }; -
Pertahankan aspect ratio Hitung dimensi untuk mempertahankan aspect ratio:
function calculateDimensions(originalWidth: number, originalHeight: number, targetWidth: number) {const aspectRatio = originalWidth / originalHeight;return {width: targetWidth,height: Math.round(targetWidth / aspectRatio)};} -
Tangani path file dengan benar Gunakan Filesystem Capacitor untuk penanganan path lintas platform:
import { Filesystem, Directory } from '@capacitor/filesystem';const inputPath = await Filesystem.getUri({directory: Directory.Documents,path: 'input.mp4'}); -
Tampilkan progress kepada pengguna Pemrosesan video bisa lambat - beri tahu pengguna:
async function processWithProgress(inputPath: string) {// Show loading indicatorshowLoading('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();}} -
Bersihkan file sementara Hapus file intermediate untuk menghemat penyimpanan:
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 neededawait Filesystem.deleteFile({ path: inputPath });return outputPath;}
Catatan Platform
Section titled “Catatan Platform”- Memerlukan iOS 11.0+
- Pemrosesan video besar mungkin memerlukan izin background task
- Menggunakan VideoToolbox iOS native untuk akselerasi hardware
Android
Section titled “Android”- Memerlukan Android 5.0 (API 21)+
- Akselerasi hardware bervariasi tergantung perangkat
- Mungkin memerlukan izin WRITE_EXTERNAL_STORAGE untuk akses file
- Tidak didukung pada platform web
Tips Performa
Section titled “Tips Performa”- Resolusi lebih rendah untuk pemrosesan lebih cepat: Dimensi lebih kecil = encoding lebih cepat
- Gunakan akselerasi hardware: Biarkan platform native mengoptimalkan encoding
- Proses di background: Jangan blokir UI selama pemrosesan video
- Monitor penggunaan memori: Video besar dapat mengonsumsi memori signifikan
- Uji pada perangkat nyata: Emulator mungkin tidak mencerminkan performa aktual