Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用express流式播放mp3文件_Javascript_Node.js_Api_Express - Fatal编程技术网

Javascript 如何使用express流式播放mp3文件

Javascript 如何使用express流式播放mp3文件,javascript,node.js,api,express,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

我正在使用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(`/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))
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);

端点是否有问题,或者我是否应该更改提取调用?

是的,您确实需要在这里进行一些额外的工作,设置几个标题。示例代码如下所示:

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))
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请求后得到的响应。根据这一点,[响应将返回一个主体,在我的例子中不是这样的。响应{type:basic,url:http://localhost:3000/speech?lang=en&text=hi%20how%20are%20you?,重定向:false,状态:200,确定:true,状态文本:确定,标题:标题,bodyUsed:false}这是否回答了您的问题?请提供一个复制问题的答案。@CodyG。如果我们按照该链接中提供的示例进行操作,获取请求会是什么样子?响应应该如何处理?获取请求?您的意思是客户机正在请求什么?响应应该如何处理?express应该如何处理?客户机应该如何处理是否处理端点发送的响应?