[nest.js] ffmpeg 사용법

김민재·2025년 4월 26일

nest.js

목록 보기
50/63

🍮 ffmpeg

모듈 다운로드

  • npm install @ffmpeg-installer/ffmpeg
  • npm install fluent-ffmpeg

모듈 import

  • import * as ffmpeg from 'fluent-ffmpeg';
    // import ffmpegInstaller from '@ffmpeg-installer/ffmpeg';

  • const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg');

  • ffmpeg.setFfmpegPath(ffmpegInstaller.path);
    import 방식으로 ffmpegInstaller을 가져오면 undefinder나온다.

    service 로직

    import * as ffmpeg from 'fluent-ffmpeg';
    // import ffmpegInstaller from '@ffmpeg-installer/ffmpeg';
    const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg');
    ffmpeg.setFfmpegPath(ffmpegInstaller.path);
    
    // 동영상 파일 이미지 제거 & 영상 음성 제거 /  음성 추출
     async processVideo(file) {
       const uploadDir = path.resolve(__dirname, 'uploads'); // 루트에 'uploads' 폴더 생성
    
       if (!fs.existsSync(uploadDir)) {
         fs.mkdirSync(uploadDir, { recursive: true });
       }
    
       // 업로드된 파일 경로 (절대 경로로 변환)
       const filePath = path.resolve(file.path); // 업로드된 파일의 절대 경로
       const outputAudioPath = path.join(uploadDir, 'audio.mp3');
       const outputVideoNoAudioPath = path.join(uploadDir, 'video_no_audio.mp4');
    
       // 음성 추출
       await new Promise((resolve, reject) => {
         ffmpeg(filePath)
           .noVideo()
           .audioCodec('libmp3lame')
           .output(outputAudioPath)
           .on('end', resolve)
           .on('error', reject)
           .run();
       });
    
       // 영상 오른쪽 이미지 제거 & 음성 제거
       await new Promise((resolve, reject) => {
         ffmpeg(filePath)
           .noAudio()
           .videoFilter('crop=iw/2:ih:0:0')
           .output(outputVideoNoAudioPath)
           .on('end', resolve)
           .on('error', reject)
           .run();
       });
     }
profile
개발 경험치 쌓는 곳

0개의 댓글