代码之家  ›  专栏  ›  技术社区  ›  MM PP

使用MediaRecorder录制5秒的音频片段,然后上载到服务器

  •  2
  • MM PP  · 技术社区  · 7 年前

    我要录制用户的麦克风5秒长的片段,并将每个片段上载到服务器。我尝试使用MediaRecorder,并以5秒的时间间隔调用start()和stop()方法,但当我连接这些录制时,在两者之间会有一个“drop”声音。因此,我尝试使用start()方法的timeslice参数录制5秒片段:

    navigator.mediaDevices.getUserMedia({ audio: { channelCount: 2, volume: 1.0, echoCancellation: false, noiseSuppression: false } }).then(function(stream) {
      const Recorder = new MediaRecorder(stream, { audioBitsPerSecond: 128000, mimeType: "audio/ogg; codecs=opus" });
      Recorder.start(5000); 
      Recorder.addEventListener("dataavailable", function(event) {
        const audioBlob = new Blob([event.data], { type: 'audio/ogg' });
        upload(audioBlob);
      });
    });
    

    但只有第一段是可播放的。我能做什么,或者怎样才能让所有的垃圾都可以播放? 我必须记录然后上传每个片段。我不能创建一个blob数组(因为用户可以记录24小时或更长时间的数据,并且数据需要在用户记录时上载到服务器上-延迟5秒)。

    谢谢您!

    1 回复  |  直到 7 年前
        1
  •  4
  •   Kaiido    7 年前


    datavailableEvent.data


    • const recorder = new MediaRecorder(stream);
      const chunks = [];
      recorder.ondataavailable = e => chunks.push(e.data);
      recorder.start(); // you don't need the timeslice argument
      setInterval(()=>{
        // here we both empty the 'chunks' array, and send its content to the server
        sendToServer(new Blob(chunks.splice(0,chunks.length)))
      }, 5000);
      

    • function record_and_send(stream) {
         const recorder = new MediaRecorder(stream);
         const chunks = [];
         recorder.ondataavailable = e => chunks.push(e.data);
         recorder.onstop = e => sendToServer(new Blob(chunks));
         setTimeout(()=> recorder.stop(), 5000); // we'll have a 5s media file
         recorder.start();
      }
      // generate a new file every 5s
      setInterval(record_and_send, 5000);
      


      ffmpeg

    推荐文章