如何在 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');

}



不幸的是,我无法弄清楚如何在 JavaScript 录制后发布。


翻翻过去那场雪
浏览 129回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript