我有一个MedaRecroder流以音频/ webm格式录制。我正在将它发送到节点服务器。我能够在req.files下的响应中看到该文件但是当我播放它时听起来有编码错误。
我正在尝试将音频文件写入服务器(理想情况下是.wav但webm会这样做)所以我可以访问和播放音频
function onRecordingReady(e) {
var audio = document.getElementById('audio');
var tag = document.getElementById('tag').value
audio.src = URL.createObjectURL(e.data);
audio.play();
var formData = new FormData()
formData.append('source', e.data);
formData.append('tag', tag);
$.ajax({
url: 'http://localhost:3300/api/kb8',
type: "POST",
data:formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
在我的服务器上,我正在处理这样的帖子
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');
const wav = require('wav');
let upload = multer();
const app = express();
const PORT = process.env.PORT || 3300;
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res){
res.send('hello world');
});
app.post('/api/kb8', upload.any(), function(req, res) {
let formData = req.body;
let files = req.files;
fs.writeFileSync('audio/audiotest.webm', req.files);
console.log('form data', formData, 'file' , files);
res.sendStatus(200);
});
继承我的控制台输出
form data { tag: 'tag', } file { fieldname: 'source',
originalname: 'blob',
encoding: '7bit',
mimetype: 'audio/webm',
buffer: <Buffer 1a 45 df a3 9f 42 86 81 01 42 f7 81 01 42 f2 81 04 42 f3 81 08 42 82 84 77 65 62 6d 42 87 81 04 42 85 81 02 18 53 80 67 01 ff ff ff ff ff ff ff 15 49 ... >,
size: 14322 }
我想到了。
Multer在请求对象(req.files)上创建一个文件数组,以便访问缓冲区并写入您必须执行此操作的文件。
fs.writeFileSync('audio / audiotest.webm',req.files [0] .buffer);
希望这有帮助。