running the formatVideoToWebpSticker function

Viewed 16

this is my code trying to convert an mp4 to webp file. for some reason its not saving the file to my folder and when I console.logged it, it sent a path to my temp folder but the file wasn't there. Tried looking it up but found nothing helpful :( how to fix this please? thank you

const path = require('path');
const Crypto = require('crypto');
const { tmpdir } = require('os');
const ffmpeg = require('fluent-ffmpeg');
const webp = require('node-webpmux');
const fs = require('fs').promises;
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const { MessageMedia } = require('whatsapp-web.js');

const media = MessageMedia.fromFilePath('./1.mp4');

async function formatVideoToWebpSticker(media) {
        if (!media.mimetype.includes('video'))
            throw new Error('media is not a video');
        const videoType = media.mimetype.split('/')[1];
        const tempFile = path.join(
            tmpdir(),
            `${Crypto.randomBytes(6).readUIntLE(0, 6).toString(36)}.webp`
        );
        const stream = new (require('stream').Readable)();
        const buffer = Buffer.from(
            media.data.replace(`data:${media.mimetype};base64,`, ''),
            'base64'
        );
        stream.push(buffer);
        stream.push(null);
        await new Promise((resolve, reject) => {
            ffmpeg(stream)
                .inputFormat(videoType)
                .on('error', reject)
                .on('end', () => resolve(true))
                .addOutputOptions([
                    '-vcodec',
                    'libwebp',
                    '-vf',
                    // eslint-disable-next-line no-useless-escape
                    'scale=\'iw*min(300/iw\,300/ih)\':\'ih*min(300/iw\,300/ih)\',format=rgba,pad=300:300:\'(300-iw)/2\':\'(300-ih)/2\':\'#00000000\',setsar=1,fps=10',
                    '-loop',
                    '0',
                    '-ss',
                    '00:00:00.0',
                    '-t',
                    '00:00:05.0',
                    '-preset',
                    'default',
                    '-an',
                    '-vsync',
                    '0',
                    '-s',
                    '512:512',
                ])
                .toFormat('webp')
                .save(tempFile)
                console.log(tempFile);
        });
        
        const data = await fs.readFile(tempFile, 'base64');
        console.log(tempFile)
        await fs.unlink(tempFile);
        return {
            mimetype: 'image/webp',
            data: data,
            filename: media.filename,
        };
    }
formatVideoToWebpSticker(media)
0 Answers
Related