Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the sample rate of a large audio file in javascript?

In javascript, I am converting mp3 data in the form of an array buffer into an object URL with window.URL.createObjectURL ... how could I determine the sample rate of the mp3 file?

I could use the web audio API to load the samples of the audio into memory, but the mp3 file is 300MB ...

Can the web audio API determine the sample rate of an audio element without creating an AudioBuffer?

like image 903
John Hoffman Avatar asked Nov 29 '25 05:11

John Hoffman


1 Answers

Set the Range header to return enough bytes to read the sampleRate. This still creates an AudioBuffer but the whole file is not downloaded.

var audioContext = new AudioContext();
var req = new XMLHttpRequest();
var url = 'http://example.com/file.mp3';
req.open('GET', url);
req.setRequestHeader('Range', 'bytes=0-640'); // enough bytes to read meta data
req.responseType = 'arraybuffer';
req.onload = function(event) {
  audioContext.decodeAudioData(this.response, function(decodedBuffer) {
    console.log(decodedBuffer.sampleRate);
  }, function(error) {
    console.log(error);
  });
};
req.send();

DEMO: http://jsfiddle.net/oxv5ykvn/

like image 182
Miguel Mota Avatar answered Dec 01 '25 23:12

Miguel Mota