我正在使用简单的开始和停止按钮在网页上录制音频。该文件存储为 blob。我希望在对后端 API 的 POST 调用正文中将此 blob 作为文件转换为 base64。
我尝试了以下代码:
'use strict'
var log = console.log.bind(console),
id = val => document.getElementById(val),
ul = id('ul'),
gUMbtn = id('gUMbtn'),
start = id('start'),
stop = id('stop'),
stream,
recorder,
counter = 1,
chunks,
media;
var mv = id('mediaVideo'),
mediaOptions = {
video: {
tag: 'video',
type: 'video/webm',
ext: '.mp4',
gUM: { video: true, audio: true }
},
audio: {
tag: 'audio',
type: 'audio/ogg',
ext: '.ogg',
gUM: { audio: true }
}
}
media = mediaOptions.audio;
navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => {
stream = _stream;
id('btns').style.display = 'inherit';
start.removeAttribute('disabled');
recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => {
chunks.push(e.data);
let blob = new Blob(chunks, { type: media.type })
, url = URL.createObjectURL(blob)
, li = document.createElement('li')
, mt = document.createElement(media.tag)
, hf = document.createElement('a');
if (recorder.state == 'inactive') makeLink(url, li, mt, hf);
log('data receiving');
var reader = new FileReader();
reader.readAsDataURL(blob);
console.log(reader);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8080/rest/api/v1/audio/submit", (JSON.stringify(reader)), true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(reader));
};
}).catch(log);
start.onclick = e => {
start.disabled = true;
stop.removeAttribute('disabled');
chunks = [];
recorder.start();
}
stop.onclick = e => {
stop.disabled = true;
recorder.stop();
start.removeAttribute('disabled');
}
function makeLink(url, li, mt, hf) {
mt.controls = true;
mt.src = url;
hf.href = url;
hf.download = `${counter++}${media.ext}`;
hf.innerHTML = `${hf.href}`;
li.appendChild(mt);
li.appendChild(hf);
ul.appendChild(li);
}
不幸的是,我无法弄清楚如何在 JavaScript 录制后发布。
您需要的onload
时候为事件监听器reader
已加载data
在它看完后file
。在该事件侦听器中handler
,您可以post
拨打电话。
let reader = new FileReader();
reader.addEventListener('load', e=>{
console.log(reader.result);
var xhttp = new XMLHttpRequest();
xhttp.open("POST"," http://localhost:8080/rest/api/v1/audio/submit", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send({data:reader.result});
});
reader.readAsDataURL(blob);
另请查看FileReader.readDataAsURL的官方文档
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句