2

Is it possible to check duration of audio file before uploading in similar way like file.size in the example below?

handleSubmit = async event =>
event.preventDefault();

if (this.file && this.file.size > config.MAX_ATTACHMENT_SIZE) {
  alert("Please pick a file smaller than" + config.MAX_ATTACHMENT_SIZE);
    return;
}
mr_storm
  • 23
  • 4

1 Answers1

7

If we're talking about the browser, yes, it is. You can use URL.createObjectURL() on your file, use that as the src for an <audio> element you create, wait for the element's canplaythrough event, then read the duration property.

As a matter of fact, that code is available in my recent answer here (and reproduced below); it should be rather easy to integrate in your code.

function computeLength(file) {
  return new Promise((resolve) => {
    var objectURL = URL.createObjectURL(file);
    var mySound = new Audio([objectURL]);
    mySound.addEventListener(
      "canplaythrough",
      () => {
        URL.revokeObjectURL(objectURL);
        resolve({
          file,
          duration: mySound.duration
        });
      },
      false,
    );
  });  
}
AKX
  • 152,115
  • 15
  • 115
  • 172
  • thanks for this, how do you clean up (removeEventListener) the even listener though? – its_tayo Jun 12 '20 at 23:17
  • It shouldn't matter here, since `mySound` itself should only remain until `resolve` is called. Are you seeing memory leaks with this? – AKX Jun 13 '20 at 13:07
  • Not really, I've just always assumed non-removal of event listeners lead to memory leaks. – its_tayo Jun 14 '20 at 07:20