几分钟后,将删除BLOB音频文件 [英] BLOB audio files are deleted after a few minutes

查看:54
本文介绍了几分钟后,将删除BLOB音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个录制语音消息并将其保存为BLOB文件的程序,但是,几分钟后,它们将无法播放.为什么会发生这种情况,我该如何解决?

I have a program that records voice messages and saves them as BLOB files, however, after a few minutes, they become unplayable. Why is this happening and how can I fix it?

代码:

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");
mt.controls = true;
mt.src = url;
mt.style.width = "100%";
mt.style.outline = "none";
hf.href = url;
hf.download = `${counter++}${media.ext}`;
hf.innerHTML = `donwload ${hf.download}`;
$("#media").append(mt);
$("#media").append(
  "<button class='btn btn-danger' style='width: 100%; margin-bottom: 1%' onclick='deleteRec()'>Delete</button><button id='sendVsMsg' class='btn btn-success' style='width: 100%'>Send</button>"
);
$("#sendVsMsg").attr("onclick", "sendRec('" + mt.src + "')");
$("#stop").toggle();
$("#start").toggle();

推荐答案

我使用了

I used the MediaRecorder API, I used inline comments to explain the how it works.

let recorder, chunks, recording; // flag
const options = {
  audio: true,
  video: false
}; // user media constraints
const button = document.getElementById('button');

button.addEventListener('click', _ => navigator.mediaDevices.getUserMedia(options).then(stream => {
  if (recording) {
    recorder.stop();
    return;
  }

  chunks = []; // Reset the data collected
  recorder = new MediaRecorder(stream); // Initialized the recorder
  recorder.start();
  recording = true;

  recorder.addEventListener('dataavailable', e => chunks.push(e.data)); // This is where the recorded data is collected.
  recorder.addEventListener('stop', _ => {
    const reader = new FileReader();

    stream.getAudioTracks()[0].stop(); // Stop the stream recording
    reader.addEventListener('load', e => fetch('Path/to/PHP', {
      mode: 'cors',
      method: 'POST',
      body: e.target.result.split(',')[1].replaceAll(' ', '+')
    }).then(response => response.text()).then(console.log));
    reader.readAsDataURL(new Blob(chunks, { type: 'audio/mp3' }));
  });
}).catch(error => {
  console.log(error);
  recording = false;
}));

<button id="button">Start/Stop Recording</button>

然后接收的PHP文件应该是这样的

Then the receiving PHP file should be something like this,

<?php
    $size = file_put_contents('audio.mp3', base64_decode(file_get_contents('php://input')));

    if ($size) echo 'Uploaded Successfully';
    else echo 'Error Uploading';

file_put_contents 的返回值> 是要上传的数据的大小,但是如果出现错误,它将返回 falsy

然后我们 echo 退出上传状态并注销收到的消息.

Then we echo out the state of the upload and log out the message recieved.

这篇关于几分钟后,将删除BLOB音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆