Jor*_*dge 6 javascript audio web-audio-api
根据我的阅读,我希望以下JavaScript代码记录"All is well",但它会遇到错误情况:
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)
}Run Code Online (Sandbox Code Playgroud)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
这可能是一个CORS问题吗?有没有其他方法来确定这个mp3文件实际上是单声道?
编辑:正如@padenot所提到的,这是源节点中的通道数,而不是实际的媒体文件
我希望有一种解决方案可以避免在记忆中解码整个音频文件.decodeAudioData()根据我的经验,需要将整个mp3解码为一个,这可能需要几秒钟.createMediaElementSource()允许您在收听时流式传输媒体和解码.
AMediaElementAudioSourceNode确实有一个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);
Run Code Online (Sandbox Code Playgroud)
是的,您需要在响应中包含 CORS 标头才能使其正常工作。