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.

60 lines (51 loc) 2.33 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); /** * Converts an audio file to a video format (MP4) and stores it in the specified folder. * @param {string} uploadPath - The directory path where the audio file and converted video will be stored. * @param {object} file - The uploaded audio file object (e.g., from a file upload request). * @returns {Promise<string>} - The path to the converted video file or an error message. */ const convertAudioToVideo = async (uploadPath, file) => { if (!file) { throw new Error('No file found, cannot upload.'); } const fName = path.parse(file.originalname).name; // Get the file name without extension const videoPath = path.join(uploadPath, `${fName}.mp4`); // Define the path for the converted video // Ensure the uploadPath exists if (!fs.existsSync(uploadPath)) { fs.mkdirSync(uploadPath, { recursive: true }); } try { // Convert the audio to video using ffmpeg await new Promise((resolve, reject) => { ffmpeg(file?.path) .output(videoPath) .videoCodec('libx264') // Set video codec (H.264 for MP4) .audioCodec('aac') // Set audio codec (AAC for MP4) .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); } }; // CommonJS export module.exports = { convertAudioToVideo }; // ES Module export export { convertAudioToVideo };