如何使用Express流式mp3文件

时间:2018-11-27 14:24:04

标签: javascript node.js api express

我正在使用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))

端点中是否有问题,还是应该更改提取调用?

1 个答案:

答案 0 :(得分: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);