javascript 如何在Chrome中为MediaRecorder录制的音频添加预定义长度?

qjp7pelc  于 2023-01-24  发布在  Java
关注(0)|答案(6)|浏览(230)

我正在用内置的MediaRecorder替换RecordRTC,以便在Chrome中录制音频。录制的音频然后在带有音频API的程序中播放。我在让audio.duration属性工作时遇到了麻烦。它说
如果视频(音频)是流式的,并且没有预定义的长度,则返回“Inf”(无限)。
使用RecordRTC时,我必须使用ffmpeg_asm.js将音频从wav转换为ogg。我猜RecordRTC在此过程中设置了预定义的音频长度。有没有办法使用MediaRecorder设置预定义的长度?

sdnqo3pr

sdnqo3pr1#

这是一个chrome bug
FF确实公开了录制媒体的持续时间,如果您确实将录制媒体的currentTime设置为大于其实际duration,则该属性在chrome ...

var recorder,
  chunks = [],
  ctx = new AudioContext(),
  aud = document.getElementById('aud');

function exportAudio() {
  var blob = new Blob(chunks);
  aud.src = URL.createObjectURL(new Blob(chunks));

  aud.onloadedmetadata = function() {
    // it should already be available here
    log.textContent = ' duration: ' + aud.duration;
    // handle chrome's bug
    if (aud.duration === Infinity) {
      // set it to bigger than the actual duration
      aud.currentTime = 1e101;
      aud.ontimeupdate = function() {
        this.ontimeupdate = () => {
          return;
        }
        log.textContent += ' after workaround: ' + aud.duration;
        aud.currentTime = 0;
      }
    }
  }
}

function getData() {
  var request = new XMLHttpRequest();
  request.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/4/4b/011229beowulf_grendel.ogg', true);
  request.responseType = 'arraybuffer';
  request.onload = decodeAudio;
  request.send();
}

function decodeAudio(evt) {
  var audioData = this.response;
  ctx.decodeAudioData(audioData, startRecording);
}

function startRecording(buffer) {

  var source = ctx.createBufferSource();
  source.buffer = buffer;
  var dest = ctx.createMediaStreamDestination();
  source.connect(dest);

  recorder = new MediaRecorder(dest.stream);
  recorder.ondataavailable = saveChunks;
  recorder.onstop = exportAudio;
  source.start(0);
  recorder.start();
  log.innerHTML = 'recording...'
  // record only 5 seconds
  setTimeout(function() {
    recorder.stop();
  }, 5000);
}

function saveChunks(evt) {
  if (evt.data.size > 0) {
    chunks.push(evt.data);
  }

}

// we need user-activation
document.getElementById('button').onclick = function(evt){
  getData();
  this.remove();
}
<button id="button">start</button>
<audio id="aud" controls></audio><span id="log"></span>

所以这里的建议是启动bug report,这样chromium的团队就需要一些时间来修复它,即使这个变通方案可以做到这一点...

hgb9j2n6

hgb9j2n62#

感谢@Kaiido发现错误并提供工作修复。
我准备了一个名为get-blob-duration的npm包,您可以安装该包以获得一个很好的Promise-wrapped函数来完成这项繁重的工作。
用法如下:

// Returns Promise<Number>
getBlobDuration(blob).then(function(duration) {
  console.log(duration + ' seconds');
});

或ECMAScript 6:

// yada yada async
const duration = await getBlobDuration(blob)
console.log(duration + ' seconds')
watbbzwu

watbbzwu3#

2016年检测到的Chrome中的一个漏洞,至今(2019年3月)仍未解决,这是导致这种行为的根本原因。在某些情况下,audioElement.duration将返回Infinity

Chrome错误信息herehere

下面的代码提供了一个解决方法来避免该错误。

用法:创建audioElement,并调用此函数一次,提供audioElement的引用。解析返回的promise时,audioElement.duration属性应包含正确的值。(它还修复了videoElements的相同问题)

/**
 *  calculateMediaDuration() 
 *  Force media element duration calculation. 
 *  Returns a promise, that resolves when duration is calculated
 **/
function calculateMediaDuration(media){
  return new Promise( (resolve,reject)=>{
    media.onloadedmetadata = function(){
      // set the mediaElement.currentTime  to a high value beyond its real duration
      media.currentTime = Number.MAX_SAFE_INTEGER;
      // listen to time position change
      media.ontimeupdate = function(){
        media.ontimeupdate = function(){};
        // setting player currentTime back to 0 can be buggy too, set it first to .1 sec
        media.currentTime = 0.1;
        media.currentTime = 0;
        // media.duration should now have its correct value, return it...
        resolve(media.duration);
      }
    }
  });
}

// USAGE EXAMPLE :  
calculateMediaDuration( yourAudioElement ).then( ()=>{ 
  console.log( yourAudioElement.duration ) 
});
u3r8eeie

u3r8eeie4#

感谢***@colxi***提供的实际解决方案,我添加了一些验证步骤(因为该解决方案工作正常,但在处理长音频文件时出现了问题)。
我花了4个小时才让它处理长音频文件,结果验证是修复的方法

function fixInfinity(media) {
          return new Promise((resolve, reject) => {
            //Wait for media to load metadata
            media.onloadedmetadata = () => {
              //Changes the current time to update ontimeupdate
              media.currentTime = Number.MAX_SAFE_INTEGER;
              //Check if its infinite NaN or undefined
              if (ifNull(media)) {
                media.ontimeupdate = () => {
                  //If it is not null resolve the promise and send the duration
                  if (!ifNull(media)) {
                    //If it is not null resolve the promise and send the duration
                    resolve(media.duration);
                  }
                  //Check if its infinite NaN or undefined //The second ontime update is a fallback if the first one fails
                  media.ontimeupdate = () => {
                    if (!ifNull(media)) {
                      resolve(media.duration);
                    }
                  };
                };
              } else {
                //If media duration was never infinity return it
                resolve(media.duration);
              }
            };
          });
        }
        //Check if null
        function ifNull(media) {
          if (media.duration === Infinity || media.duration === NaN || media.duration === undefined) {
            return true;
          } else {
            return false;
          }
        }

    //USAGE EXAMPLE
            //Get audio player on html
            const AudioPlayer = document.getElementById('audio');
            const getInfinity = async () => {
              //Await for promise
              await fixInfinity(AudioPlayer).then(val => {
                //Reset audio current time
                AudioPlayer.currentTime = 0;
                //Log duration
                console.log(val)
              })
            }
ltskdhd1

ltskdhd15#

我 Package 了webm-duration-fix包来解决webm长度问题,它可以在nodejs和web浏览器中使用,以支持超过2GB的视频文件,而不会占用太多内存。
用法如下:

import fixWebmDuration from 'webm-duration-fix';

const mimeType = 'video/webm\;codecs=vp9';
const blobSlice: BlobPart[] = [];

mediaRecorder = new MediaRecorder(stream, {
  mimeType
});

mediaRecorder.ondataavailable = (event: BlobEvent) => {
  blobSlice.push(event.data);
}

mediaRecorder.onstop = async () => {  
    // fix blob, support fix webm file larger than 2GB
    const fixBlob = await fixWebmDuration(new Blob([...blobSlice], { type: mimeType }));
    // to write locally, it is recommended to use fs.createWriteStream to reduce memory usage
    const fileWriteStream = fs.createWriteStream(inputPath);
    const blobReadstream = fixBlob.stream();
    const blobReader = blobReadstream.getReader();

    while (true) {
      let { done, value } = await blobReader.read();
      if (done) {
        console.log('write done.');
        fileWriteStream.close();
        break;
      }
      fileWriteStream.write(value);
      value = null;
    }
    blobSlice = [];
};
at0kjp5o

at0kjp5o6#

//如果要完整修改视频文件,可以使用webmFixDuration包,其他方法只在video标签上应用显示级别,使用此方法可以修改完整的视频文件
webmFixDuration github示例

mediaRecorder.onstop = async () => {
        const duration = Date.now() - startTime;
        const buggyBlob = new Blob(mediaParts, { type: 'video/webm' });
    
        const fixedBlob = await webmFixDuration(buggyBlob, duration);
        displayResult(fixedBlob);
      };

相关问题