根据我所读到的内容,我希望以下 JavaScript 代码能够记录“一切都很好”,但它却遇到了错误情况:
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.github.io/simple-snippets-console/snippet.js"></script>
这是怎么回事?
这可能是 CORS 问题吗?还有其他方法可以确定这个 mp3 文件实际上是单声道吗?
Edit:正如@padenot提到的,这是源节点中的通道数,而不是实际的媒体文件
澄清
我希望有一个解决方案可以避免解码内存中的整个音频文件。decodeAudioData()
根据我的经验,需要一次解码整个 mp3,这可能需要几秒钟。createMediaElementSource()
允许您在收听时流式传输媒体并进行解码。
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 标头才能使其正常工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)