Vueでアップロードされた動画ファイルの再生時間を取得する方法

Vue.js と Element UI の el-upload コンポーネントを活用して、ユーザーがアップロードした MP4 動画ファイルの再生時間を取得する実装方法を紹介します。

HTML テンプレート

<el-upload
  class="upload-demo"
  :action="actionUrl"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
>
  <button class="ce-button not-hover primary">
    <i class="ce-icon_upload"></i>
    <span>再アップロード</span>
  </button>
</el-upload>

<!-- 再生時間を一時的に格納する隠し入力フィールド -->
<input type="hidden" ref="videoDurationRef" />

JavaScript 実装(Vue メソッド内)

beforeAvatarUpload(file) {
  const allowedExtensions = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'mp4'];
  const fileName = file.name || '';
  const ext = fileName.split('.').pop()?.toLowerCase();

  if (!allowedExtensions.includes(ext)) {
    this.$notify({
      title: 'エラー',
      message: '許可されている形式は doc/docx/xls/xlsx/ppt/pptx/pdf/mp4 のみです。',
      type: 'error',
      duration: 3000
    });
    return false;
  }

  // ファイルサイズ制限
  const sizeInBytes = file.size;
  if (['doc', 'docx', 'ppt', 'pptx'].includes(ext) && sizeInBytes > 10 * 1024 * 1024) {
    this.$notify({
      title: 'エラー',
      message: 'Word および PowerPoint ファイルは 10MB までです。',
      type: 'error',
      duration: 3000
    });
    return false;
  }

  if (ext === 'mp4') {
    const objectUrl = URL.createObjectURL(file);
    const video = document.createElement('video');
    video.preload = 'metadata';

    video.onloadedmetadata = () => {
      const durationInSeconds = video.duration; // 例: 182.36
      this.$refs.videoDurationRef.value = Math.floor(durationInSeconds); // 整数に変換して保存
      URL.revokeObjectURL(objectUrl); // メモリリーク防止
    };

    video.onerror = () => {
      console.error('動画のメタデータ読み込みに失敗しました。');
      URL.revokeObjectURL(objectUrl);
    };

    // メタデータ読み込みをトリガー
    video.src = objectUrl;
  }

  // ファイル名とサイズを親コンポーネントに渡す
  this.$parent.$data.wFileName = file.name;
  this.$parent.$data.wSize = (file.size / 1024).toFixed(2);
}

上記コードでは、video 要素を使用して動画のメタデータを読み込み、再生時間を取得しています。Audio 要素でも同様の動作が可能ですが、動画ファイルには video 要素の方がより適しています。また、URL.revokeObjectURL() を呼び出すことで、不要になったオブジェクト URL を解放し、メモリ使用量を最適化しています。

タグ: vue.js Element UI javascript video duration

5月30日 17:08 投稿