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

时间:2016-07-18 17:54:28

标签: javascript google-chrome html5-audio mediarecorder recordrtc

我正在使用内置的MediaRecorder替换RecordRTC,以便在Chrome中录制音频。然后在带有音频api的程序中播放录制的音频。我无法使audio.duration属性工作。它说

  

如果视频(音频)是流式传输的并且没有预定义的长度,那么" Inf" (无限)返回。

使用RecordRTC,我不得不使用ffmpeg_asm.js将音频从wav转换为ogg。我的猜测是在RecordRTC设置预定义音频长度的过程中的某个地方。有没有办法使用MediaRecorder设置预定义的长度?

4 个答案:

答案 0 :(得分:24)

这是chrome bug

FF确实会显示录制媒体的持续时间,如果您将录制媒体的currentTime设置为高于其实际duration,则该属性可用于Chrome ... < / p>

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

function exportAudio() {
  var blob = new Blob(chunks, {
    type: 'audio/ogg'
  });
  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);
  }

}



getData();
&#13;
<audio id="aud" controls></audio><span id="log"></span>
&#13;
&#13;
&#13;

所以这里的建议是为bug report加注星标,以便铬的团队花一些时间来修复它,即使这种解决方法可以解决问题......

答案 1 :(得分:1)

感谢@Kaiido识别错误并提供工作修复。

我准备了一个名为get-blob-duration的npm包,你可以安装它来获得一个很好的Promise包装函数来完成这项肮脏的工作。

用法如下:

// 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')

答案 2 :(得分:1)

感谢 @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)
              })
            }

答案 3 :(得分:0)

Chrome的一个错误在2016年被发现,但今天仍然开放(2019年3月),是此行为的根本原因。在某些情况下,audioElement.duration将返回Infinity

  

Chrome Bug 信息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 ) 
});