首页 > 解决方案 > 如何在 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 录制后发布。

标签: javascriptpost

解决方案


您需要一个onload 事件侦听器,用于在reader读取. 在那个事件监听器中,您可以拨打电话。datafilehandlerpost

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的官方文档


推荐阅读