【问题标题】:How can I detect the number of audio channels in an mp3 in an <audio> tag?如何在 <audio> 标签中检测 mp3 中的音频通道数?
【发布时间】:2015-09-29 03:20:20
【问题描述】:

根据我的阅读,我预计以下 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 文件实际上是单声道的吗?

编辑:正如@padenot 提到的,这是源节点中的频道数,而不是实际的媒体文件

澄清

我希望有一种解决方案可以避免在内存中解码整个音频文件。 decodeAudioData(),根据我的经验,需要一次解码整个 mp3,这可能需要几秒钟。 createMediaElementSource() 允许您在收听时流式传输媒体和解码。

【问题讨论】:

    标签: javascript audio web-audio-api


    【解决方案1】:

    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 标头才能使其正常工作。

    【讨论】:

    • 其实MediaElementAudioSourceNode.channelCount是一个有效的属性,但并不反映媒体源中的频道数量。 MediaElementAudioSourceNode
    • 我刚刚在便签本中尝试过。它缺少xhr.send(null);,它应该是decodedBuffer.numberOfChannels。然后就可以了。
    • decodeAudioData() 在任何有意义大小的压缩音频文件上都可能非常慢。我更喜欢一种无需解码内存中的整个 mp3 即可得出计数的解决方案。
    • 只需滚动您自己的 JS mp3 解析器,只需进行几次位移和偏移计算即可确定通道数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2012-10-23
    • 2020-05-22
    相关资源
    最近更新 更多