【问题标题】:How do I stream an mp3 file with express如何使用 express 流式传输 mp3 文件
【发布时间】:2018-11-27 14:24:04
【问题描述】:

我正在使用gTTS 模块将文本转换为.mp3 暂时保存。保存后,我尝试流式传输文件,但是当我查看端点返回的响应对象时,arraybuffer 看起来是空的。

const express = require('express')
    , router = express.Router()
    , bodyParser = require('body-parser')
    , gtts = require('node-gtts')('en')
    , path = require('path')
    , filePath = path.join(__dirname, 'temp', 'temp.mp3')
    , fs = require('fs')
    , ms = require('mediaserver')
router.use(bodyParser.urlencoded({
    extended: true
}));
router.use(bodyParser.json());

router.get('/speech', function(req, res) {
    console.log("query", req.query.text);
    saveFile(req.query.text,req.query.lang)
    .then(response => {
        console.log('looking for file', filePath)
        fs.exists(filePath, (exists) => {
            if (exists) {
                // console.log('going to stream');
                // ms.pipe(req, res, filePath);
                // console.log("findigh");
                const stat = fs.statSync(filePath)
                const fileSize = stat.size
                const range = req.headers.range
                console.log('size ', fileSize);
                if (range) {
                    const parts = range.replace(/bytes=/, "").split("-")
                    const start = parseInt(parts[0], 10)
                    const end = parts[1] ? parseInt(parts[1], 10) : fileSize-1
                    const chunksize = (end-start)+1
                    const file = fs.createReadStream(path, {start, end})
                    const head = {
                        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                        'Accept-Ranges': 'bytes',
                        'Content-Length': chunksize,
                        'Content-Type': 'audio/mp3',
                    }
                    res.writeHead(206, head);
                    file.pipe(res);
                }  else {
                    const head = {
                        'Content-Length': fileSize,
                        'Content-Type': 'audio/mp3',
                    }
                    res.writeHead(200, head)
                    fs.createReadStream(filePath).pipe(res)
                }
            } else {
                console.log('file not found');
                res.send('Error - 404');
                res.end();
            }
        })
    })
    .catch(err => {
        console.log('error in saving file' ,err);
    });
});

const saveFile = (text, language) => {
    return new Promise((resolve, reject) => {
        gtts.save(filePath, text, function() {
            console.log('create file')
            resolve("done");
        })
    });
}
module.exports = router`

fetch 调用如下所示:

fetch(`/speech?lang=en&text=${translationBody.value}`, {
  method:'GET',
  headers: new Headers({'content-type': 'application/json'})
})
  .then(res => res)
  .then(res => console.log(res))
  .catch(err => console.log('err', err))

端点有问题还是我应该更改我的 fetch 调用?

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/questions/49524238/…
  • 请提供重现问题的Minimal, Complete, and Verifiable example
  • @CodyG。如果我们按照该链接中提供的示例进行操作,获取请求会是什么样子?应如何处理响应?
  • "获取请求" ?你的意思是客户要求什么? “响应应该如何处理”---是快递处理的?
  • 客户端应该如何处理端点发送的响应?

标签: javascript node.js api express


【解决方案1】:

是的,你确实需要一些额外的步法,设置几个头球。示例代码如下所示:

const http = require('http');
const fileSystem = require('fs');
const path = require('path');

http.createServer(function(request, response) {
  const filePath = path.join(__dirname, 'file.mp3');
  const stat = fileSystem.statSync(filePath);

  response.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': stat.size
  });

  const readStream = fileSystem.createReadStream(filePath);
  readStream.pipe(response);
})
.listen(3000);

【讨论】:

  • 这看起来不像express。 . .
  • 我确实尝试过,但它似乎不起作用。这是我在向负责流式传输音频的端点发出 GET 请求后得到的响应。据此,[medium.com/@bitshadow/… 回复将得到一个身体,但在我的情况下并非如此。 Response { type: "basic", url: "http://localhost:3000/speech?lang=en&text=hi%20how%20are%20you?", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }
猜你喜欢
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多