콘텐츠로 건너뛰기

시작하기

  1. 패키지 설치

    Terminal window
    npm i @capgo/capacitor-ffmpeg
  2. 네이티브 프로젝트와 동기화

    Terminal window
    npx cap sync

플러그인을 가져와서 비디오를 다시 인코딩하는 데 사용합니다:

import { CapacitorFFmpeg } from '@capgo/capacitor-ffmpeg';
// 사용자 정의 설정으로 비디오 다시 인코딩
const processVideo = async () => {
await CapacitorFFmpeg.reencodeVideo({
inputPath: '/path/to/input/video.mp4',
outputPath: '/path/to/output/video.mp4',
width: 1280,
height: 720,
bitrate: 2000000 // 선택 사항: 2 Mbps
});
};
// 플러그인 버전 가져오기
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 // 선택 사항: 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 {
/**
* 파일 크기를 줄이기 위해 비디오 압축
*/
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;
}
}
/**
* 특정 크기로 비디오 크기 조정
*/
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;
}
/**
* 비디오의 썸네일 품질 버전 생성
*/
async createThumbnailVideo(inputPath: string): Promise<string> {
return this.compressVideo(inputPath, 'low');
}
/**
* 여러 비디오를 일괄 처리
*/
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. 적절한 비트레이트 사용 해상도 및 사용 사례에 따라 비트레이트를 선택:

    // 모바일 공유 (낮은 대역폭)
    const lowQuality = { width: 640, height: 360, bitrate: 500000 };
    // 표준 품질
    const standardQuality = { width: 1280, height: 720, bitrate: 2000000 };
    // 고품질
    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) {
    // 로딩 표시기 표시
    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
    });
    // 더 이상 필요하지 않은 경우 원본 제거
    await Filesystem.deleteFile({ path: inputPath });
    return outputPath;
    }
  • iOS 11.0 이상 필요
  • 대용량 비디오 처리는 백그라운드 작업 권한이 필요할 수 있습니다
  • 하드웨어 가속을 위해 네이티브 iOS VideoToolbox 사용
  • Android 5.0 (API 21) 이상 필요
  • 하드웨어 가속은 기기에 따라 다릅니다
  • 파일 액세스를 위해 WRITE_EXTERNAL_STORAGE 권한이 필요할 수 있습니다
  • 웹 플랫폼에서 지원되지 않음
  1. 더 빠른 처리를 위해 해상도 낮추기: 더 작은 크기 = 더 빠른 인코딩
  2. 하드웨어 가속 사용: 네이티브 플랫폼이 인코딩을 최적화하도록 허용
  3. 백그라운드에서 처리: 비디오 처리 중 UI를 차단하지 마세요
  4. 메모리 사용량 모니터링: 대용량 비디오는 상당한 메모리를 소비할 수 있습니다
  5. 실제 기기에서 테스트: 에뮬레이터는 실제 성능을 반영하지 않을 수 있습니다