javascript - 如何在 JavaScript 中将 ogg 音频文件发布到 API?
问题描述
我正在使用简单的开始和停止按钮在网页上录制音频。该文件存储为 blob。我希望这个 blob 作为文件在对我的后端 API 的 POST 调用的主体中转换为 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);
推荐阅读
- amazon-s3 - 用于使用代理服务器上传到 S3 的 aws 请求标头中的 Java Proxy-Authorization
- logging - 如何将 Azure DataFactory 日志存储到 ApplicationInsights
- javascript - 如何使用特定索引列表视图添加选项
- excel - 将excel范围作为图片粘贴到ppt中的最佳方法是什么
- javascript - 将复选框动态添加到 DOM 的有线问题
- sql - SQL Server - 跨行汇总日期范围,同时保留间隙
- laravel - 工厂的增量编号,Laravel
- python - gitlab runner pytest 失败,但显示工作成功
- javascript - jQuery DataTable 添加动态列
- javascript - 使用javascript将div高度设置为图像高度