How to determine the number of audio channels in mp3 in the <audio> tag?

From what I read, I expect the following JavaScript code to write “Everything is fine,” but instead it addresses an error:

var audio = document.createElement('audio');
var ctx = new window.AudioContext();
var source = ctx.createMediaElementSource(audio);
audio.src = 'http://www.mediacollege.com/audio/tone/files/440Hz_44100Hz_16bit_30sec.mp3';
// As @padenot mentioned, this is the number of channels in the source node, not the actual media file
var chans = source.channelCount;
if(chans == 1) {
  snippet.log("All is well");
} else {
  snippet.log("Expected to see 1 channel, instead saw: " + chans)
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Run code

What's happening?

Is this possibly a CORS problem? Is there any other way to determine that this mp3 file is essentially mono?

Edit: As @padenot mentioned, this is the number of channels in the source node, not the actual media file

Explanation

I would like a solution that avoids decoding the entire audio file in memory. decodeAudioData(), in my experience, requires decoding all mp3 on one, which may take a few seconds. createMediaElementSource()Allows you to transfer media files and decode them when listening.

+4
1

A MediaElementAudioSourceNode channelCount, AudioNode, HTMLMEdiaElement.

, :

var xhr = new XMLHttpRequest();
xhr.open('GET', "file.mp3", true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
  var cx = new AudioContext() ;
  cx.decodeAudioData(xhr.response, function(decodedBuffer) {
    console.log(decodedBuffer.numberOfChannels);
  });
}
xhr.send(null);

, CORS , .

+2

Source: https://habr.com/ru/post/1609408/


All Articles