使用网络录音机需要将音频保存到服务器

时间:2020-06-05 19:55:07

标签: javascript php audio

我有网络录音机:https://github.com/mdn/web-dictaphone/

我的目标是使它像默认情况下一样工作,但是我想添加一个保存按钮,将记录的文件保存到wordpress服务器上。

有人对此有任何建议吗?这是录制后执行的代码, 我想我需要对audioURL做一些事情,并在php中使用诸如file_put_contents()之类的东西。我不确定是否需要转换为base64或其他内容?谢谢您的任何帮助。

  mediaRecorder.onstop = function(e) {
  console.log("data available after MediaRecorder.stop() called.");

  const clipName = prompt('Enter a name for your sound clip?','My unnamed clip');

  const clipContainer = document.createElement('article');
  const clipLabel = document.createElement('p');
  const audio = document.createElement('audio');
  const deleteButton = document.createElement('button');

  clipContainer.classList.add('clip');
  audio.setAttribute('controls', '');
  deleteButton.textContent = 'Delete';
  deleteButton.className = 'delete';

  if(clipName === null) {
    clipLabel.textContent = 'My unnamed clip';
  } else {
    clipLabel.textContent = clipName;
  }

  clipContainer.appendChild(audio);
  clipContainer.appendChild(clipLabel);
  clipContainer.appendChild(deleteButton);
  soundClips.appendChild(clipContainer);

  audio.controls = true;
  const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
  chunks = [];
  const audioURL = window.URL.createObjectURL(blob);
  audio.src = audioURL;
  console.log("recorder stopped");

  deleteButton.onclick = function(e) {
    let evtTgt = e.target;
    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
  }

  clipLabel.onclick = function() {
    const existingName = clipLabel.textContent;
    const newClipName = prompt('Enter a new name for your sound clip?');
    if(newClipName === null) {
      clipLabel.textContent = existingName;
    } else {
      clipLabel.textContent = newClipName;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

不需要转换为base64,只需将blob附加到FormData类的实例并发送。

var formData = new FormData();
formData.append('attachment', blob);

var request = new XMLHttpRequest();
request.open('POST', 'URL', true); // edit URL
request.onload = function() { console.log("Status: %s", request.responseText) };
request.send(formData);

在后端,可以像常规上载过程一样使用$_FILESmove_uploaded_file()来存档接收。

相关问题