如何将OGG音频文件发布到JavaScript中的API



我在一个简单的启动和停止按钮的网页上录制音频。该文件存储为斑点。我希望将此斑点作为文件转换为Base64在帖子正文中的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事件侦听器,因为readerfile阅读后加载了data。在这种情况下,侦听器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

的官方文档

最新更新