You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript判断WAV文件为单声道或立体声?适配WaveSurfer

解决WAV文件声道数判断及WaveSurfer适配方案

方法1:通过WaveSurfer实例获取声道信息

WaveSurfer加载音频完成后,可通过其底层Web Audio API节点直接获取声道数:

// 假设已初始化wavesurfer实例
wavesurfer.on('ready', function() {
  const sourceNode = wavesurfer.getSource();
  const channelCount = sourceNode.channelCount;
  
  if (channelCount === 1) {
    // 单声道,隐藏声道静音控制元素
    document.getElementById('left-mute-btn').style.display = 'none';
    document.getElementById('right-mute-btn').style.display = 'none';
    // 禁用拆分声道相关逻辑
    disableChannelSplit();
  } else {
    // 立体声,保持功能可用
    enableChannelSplit();
  }
});

getSource()返回WaveSurfer使用的音频源节点,channelCount属性直接对应音频的声道数,无需额外解析文件。

方法2:加载前直接解析WAV文件头部

如果需要在WaveSurfer加载前就判断声道数,可读取WAV文件的二进制头部信息(仅需前44字节):

function getWavChannelCount(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function(e) {
      const dataView = new DataView(e.target.result);
      // WAV格式中,声道数存储在偏移量22的位置,占2字节(小端字节序)
      const channelCount = dataView.getUint16(22, true);
      resolve(channelCount);
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file.slice(0, 44));
  });
}

// 用户选择文件后的处理示例
document.getElementById('audio-file-input').addEventListener('change', async function(e) {
  const file = e.target.files[0];
  if (file?.type === 'audio/wav') {
    const channels = await getWavChannelCount(file);
    if (channels === 1) {
      // 单声道,提前隐藏控制栏
      document.getElementById('channel-controls').style.display = 'none';
    }
    // 加载文件到WaveSurfer
    wavesurfer.loadBlob(file);
  }
});

WAV文件的头部规范中,偏移量22的位置固定存储声道数(1=单声道,2=立体声),这种方式无需等待音频加载完成就能判断。

适配声道静音逻辑

在你的声道静音控制函数中加入判断,避免非立体声文件触发无效操作:

function toggleMute(channel) {
  const channelCount = wavesurfer.getSource().channelCount;
  if (channelCount !== 2) return; // 非立体声直接返回
  
  // 原有立体声静音逻辑代码...
}

内容的提问来源于stack exchange,提问作者KimJE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:35:26