首页 > 解决方案 > 有没有办法流式下载正在 nodejs 服务器上转换的 mp3 文件?

问题描述

我正在寻找一种将 url 发送到 nodejs 服务器并使用 mp3 文件下载响应用户的方法。

我搜索了一些示例,并阅读了有关请求和响应的信息,但我不确定问题到底是什么。

这是 HTML 的 Javascript:

    var downloadBtn = document.querySelector('.download_button');
    var URLinput = document.querySelector('#myUrl');

    downloadBtn.addEventListener('click', () => {
        console.log(`URL: ${URLinput.value}`);
        sendURL(URLinput.value);
    });

    function sendURL(URL) {
        window.location.href = `http://localhost:4000/download?URL=${URL}`;
    }

这是 Nodejs 服务器的 Javascript:

const express = require('express');
const cors = require('cors');
const ytdl = require('ytdl-core');
const app = express();
const ffmpeg = require('fluent-ffmpeg')
app.use(cors());

app.listen(4000, () => {
    console.log('Server Works !!! At port 4000');
});

app.get('/download', (req,res) => {
var URL = req.query.URL;

res.header('Content-Disposition', 'attachment; filename="file.mp3"');
let stream = ytdl(URL, { 
  quality: 'highestaudio',
}); //HERE THE STREAM FILE IS SELECTED TO BE CONVERTED TO MP3

ffmpeg(stream)
  .audioBitrate(128)
  .pipe(res); // HERE IS CONVERTED AND WHERE I WANT IT TO SEND IT AS A DOWNLOAD TO THE USER.
});

我希望它能够流式下载文件,但它却让我到 nodejs 服务器页面到 /download/url_to_vid

标签: node.jsffmpeg

解决方案


推荐阅读