UNPKG

convert-audio-to-video-mpeg

Version:

A package for converting audio files to video/MPEG format to ensure cross-platform compatibility, especially for Android, iOS, and Safari browsers.

43 lines (37 loc) 1.72 kB
import fs from 'fs'; import path from 'path'; import ffmpeg from 'fluent-ffmpeg'; import ffmpegPath from 'ffmpeg-static'; // Set the ffmpeg path for fluent-ffmpeg to use ffmpeg.setFfmpegPath(ffmpegPath); export const convertAudioToVideo = async (uploadPath, file) => { if (!file) { throw new Error('No file found, cannot upload.'); } const fName = file.originalname ? path.parse(file.originalname).name : 'mkaudio'; const videoPath = path.join(uploadPath, `${fName}.mpeg`); // Define the path for the converted video try { // Convert the audio to video using ffmpeg await new Promise((resolve, reject) => { ffmpeg(file?.path) .output(videoPath) .videoCodec('mpeg2video') // MPEG video codec (mp4 .videoCodec('libx264') ) .audioCodec('mp2') // MPEG audio codec (mp4 .audioCodec('aac') ) .on('start', (commandLine) => { console.log('FFmpeg command:', commandLine); // Log the full ffmpeg command }) .on('error', (err, stdout, stderr) => { console.error('FFmpeg error:', err); console.error('FFmpeg stdout:', stdout); console.error('FFmpeg stderr:', stderr); // Capture detailed error messages reject(err); }) .on('end', resolve) // Resolve once conversion is done .run(); }); console.log('Video conversion completed:', videoPath); return videoPath; // Return the path to the converted video file } catch (error) { throw new Error('Error in conversion: ' + error.message); } };