You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WhatsApp Web JS中使用formatVideoToWebpSticker函数将视频转换为WebP文件

使用formatVideoToWebpSticker将视频转为WebP以提升WhatsApp Web JS发送速度

我最近在折腾WhatsApp Web JS的媒体发送效率,发现直接发视频要等5秒左右,换成WebP格式发送速度快了不少。于是我从官方文档的Util文件里扒了这个formatVideoToWebpSticker函数,专门用来把视频媒体转换成WebP格式,下面是完整的实现代码,以及我整理的关键细节:

const path = require('path');
const { tmpdir } = require('os');
const Crypto = require('crypto');
const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs').promises;

/**
 * Formats a video to webp
 * @param {MessageMedia} media
 * 
 * @returns {Promise<MessageMedia>} media in webp format
 */
static async 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);
  });
  const data = await fs.readFile(tempFile, 'base64');
  await fs.unlink(tempFile);
  return {
    mimetype: 'image/webp',
    data: data,
    filename: media.filename,
  };
}

关键细节说明

  • 输入校验:函数第一行就检查媒体类型,确保传入的是视频,避免无效输入导致后续处理出错。
  • 临时文件管理:用系统临时目录+随机生成的文件名创建WebP临时文件,既安全又不会和其他文件冲突,处理完还会自动删除,避免磁盘占用。
  • 媒体数据转换:把MessageMedia里的base64编码数据转换成Buffer,再封装成可读流,这是ffmpeg能处理的格式。
  • FFmpeg核心参数:这部分是转换的灵魂:
    • 用libwebp编码,输出格式设为webp
    • 视频滤镜做了缩放、透明背景填充、设置帧率等操作,让输出的WebP符合贴纸的尺寸规范
    • 截取视频前5秒内容、禁用音频、开启循环播放,完全适配WhatsApp贴纸的使用场景
  • 返回格式:最后返回的对象和MessageMedia结构一致,直接就能传给WhatsApp Web JS的发送接口使用。

内容的提问来源于stack exchange,提问作者Shahar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:57:35