コンテンツへスキップ

はじめに

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

プラットフォームに関する注意事項

Section titled “プラットフォームに関する注意事項”
  • iOS 11.0+が必要
  • 大きなビデオの処理にはバックグラウンドタスクの許可が必要な場合があります
  • ハードウェアアクセラレーションにネイティブiOS VideoToolboxを使用
  • Android 5.0 (API 21)+が必要
  • ハードウェアアクセラレーションはデバイスによって異なります
  • ファイルアクセスにWRITE_EXTERNAL_STORAGE権限が必要な場合があります
  • webプラットフォームではサポートされていません
  1. より高速な処理のために解像度を下げる: 寸法が小さいほどエンコードが速くなります
  2. ハードウェアアクセラレーションを使用: ネイティブプラットフォームにエンコードの最適化を任せます
  3. バックグラウンドで処理: ビデオ処理中にUIをブロックしないでください
  4. メモリ使用量を監視: 大きなビデオは大量のメモリを消費する可能性があります
  5. 実機でテスト: エミュレーターは実際のパフォーマンスを反映しない場合があります