DeepSeek前端调研-第二篇

198 阅读1分钟

背景

在开发过程中,AI团队他们需要语音格式为opus,但是h5录音的格式为webm,这就需要ffmpeg来进行格式转换,为了验证这一技术可行性,就写了个demo验证下。

安装ffmpeg

以windows举例,在官网下载安装包:www.gyan.dev/ffmpeg/buil… image.png 点击Windows builds from gyan.dev,进入下图,点击ffmpeg-git-full.7z,就会下载安装包,解压即可使用。 image.png 配置PATH环境变量
image.png
验证是否安装成功,在cmd里输入ffmpeg -version,下图即为安装成功 image.png

实现过程

npm安装核心依赖,fluent-ffmpeg是简化库,@ffmpeg-installer/ffmpeg用于获取安装路径。

npm install fluent-ffmpeg @ffmpeg-installer/ffmpeg

下面是nodejs代码

const http = require('http');
const path = require('path');
const ffmpeg = require('fluent-ffmpeg');
// 设置ffmpeg安装包路径
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
ffmpeg.setFfmpegPath(ffmpegPath);
 
// 创建HTTP服务器并监听3000端口
const server = http.createServer(async (req, res) => {
    // 假设你已经有一个 WebM 格式的 Blob 文件
    const inputBlobPath = path.join(__dirname, 'recording.webm'); // 输入文件路径
    const outputOpusPath = path.join(__dirname, 'output.opus'); // 输出文件路径
    // 转换为 Opus
    const opusFilePath = await convertWebMToOpus(inputBlobPath, outputOpusPath);
    console.log('Opus 文件已生成:', opusFilePath);
});
 
server.listen(3000, () => {
    console.log('Proxy server is listening on port 3000');
});

// webm转opus
function convertWebMToOpus(inputPath, outputPath) {
  return new Promise((resolve, reject) => {
    ffmpeg(inputPath)
      .output(outputPath)
      .audioCodec('libopus') // 指定音频编码器为 libopus
      .on('end', () => {
        console.log('转换完成:', outputPath);
        resolve(outputPath);
      })
      .on('error', (err) => {
        console.error('转换失败:', err.message);
        reject(err);
      })
      .run();
  });
}