How can I detect the number of audio channels in an mp3 in an <audio> tag?

六眼飞鱼酱① 提交于 2019-12-05 07:24:22

A MediaElementAudioSourceNode does have a channelCount attribute, but it refers to the number of channel of the AudioNode, not of the underlying HTMLMEdiaElement.

Instead, you can decode the buffer, and query its channel count, like so:

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);

And yes, you need CORS headers in the response for this to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!