# 测试音频谱

低音响起时，左侧的柱条升高。切换到高音后，最高柱向右移动，峰值频率也随之改变。

## 试一试

点按 220 Hz 播放轻柔的测试音，再切换到 880 Hz，比较峰值位置，然后点按“停止发声”。

## 交互细节

通过 Web Audio 生成选中的正弦音。每次分析 8192 个采样点，把 80 至 2000 Hz 的范围分为 52 个频段。受频率分辨率影响，测量峰值可能相差几赫兹。停止声音后柱条短暂衰减；开启减弱动态效果时立即归零。

## 各平台的操作方式

- iOS · 轻点 220 Hz，再点 880 Hz。比较峰值位置，然后轻点“停止发声”。
- Android · 轮流点按两个频率按钮，随后点按“停止发声”结束播放。
- PC · 按 Tab 移至频率按钮并按回车。可用同样方式操作“停止发声”。

## 适用场景

查看声音信号中哪些频率的能量最强。

## 实现要求

> 用相同音量播放两个正弦音。分析实际声音来绘制频谱，显示峰值频率，停止声音后让柱条落下。

## 来源与致谢

[MDN · AnalyserNode.getByteFrequencyData](<https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData>)

## 独立 HTML 示例

将以下代码保存为 HTML 文件，用浏览器打开即可离线体验。

```html
<!doctype html>
<html lang="zh-Hans" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>두 음의 스펙트럼</title>
<style>
*{box-sizing:border-box} :root{color-scheme:light;font:15px/1.45 system-ui,sans-serif;color:#21322c;background:#eae9dd}
body{margin:0}main{width:min(760px,100%);margin:auto;padding:clamp(12px,3vw,24px)}
header,.meter,footer{display:flex;align-items:baseline;justify-content:space-between;gap:6px 14px;flex-wrap:wrap}
h1{font-size:clamp(23px,4vw,36px);letter-spacing:-.055em;line-height:1.1;margin:0}header span{color:#495a4c;font-size:12px}
.instrument{margin-top:12px;overflow:hidden;background:#172e2a;color:#e4eedf;border:1px solid #203a31;border-radius:13px;box-shadow:0 2px 0 #bfc2af}
.meter{padding:11px 16px 0;align-items:center}.meter label{font-size:12px;color:#bfcfc2}.meter output{font:bold clamp(18px,3vw,26px)/1.1 ui-monospace,monospace;color:#c5f17b;font-variant-numeric:tabular-nums}
svg{display:block;width:100%;height:auto}.axis{fill:#bfd2c3;font:13px ui-monospace,monospace}.guide{stroke:#5e796a;stroke-width:1;stroke-dasharray:3 5}
.controls{display:flex;gap:7px;flex-wrap:wrap;margin:15px 0 8px}button{min-height:44px;padding:8px 16px;border:1px solid #8c9989;border-radius:7px;background:#f7f6ec;color:#20352e;font:600 15px system-ui;cursor:pointer}
button[aria-pressed="true"]{background:#264b40;color:#f5f6e4;border-color:#264b40}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:3px solid #ae541d;outline-offset:3px}
footer{align-items:center}#state{font-weight:700;color:#304e40;font-size:14px}#hint{margin:5px 0 0;font-size:13px;color:#526054}
@media(max-width:390px){button{padding-inline:11px}.axis{font-size:17px}}
</style>
</head><body><main>
<header><h1 id="title">두 음의 스펙트럼</h1><span data-i="kind">주파수 분석</span></header>
<section class="instrument" aria-labelledby="title">
  <div class="meter"><label for="peak" data-i="peak">가장 강한 주파수</label><output id="peak" aria-live="off">— Hz</output></div>
  <svg id="plot" viewBox="0 0 600 223" role="img" aria-labelledby="chart-title chart-desc">
    <title id="chart-title" data-i="chart">시험음의 주파수별 세기</title><desc id="chart-desc" data-i="desc">왼쪽이 낮은 음, 오른쪽이 높은 음입니다. 막대 높이가 주파수 구간별 세기를 나타냅니다.</desc>
    <defs><pattern id="grid" width="26" height="30" patternUnits="userSpaceOnUse"><path d="M26 0H0V30" fill="none" stroke="#345247" stroke-width="1"/></pattern><linearGradient id="bar" x1="0" y1="1" x2="0" y2="0"><stop stop-color="#529979"/><stop offset="1" stop-color="#d8f57b"/></linearGradient></defs>
    <rect x="24" y="16" width="552" height="165" fill="url(#grid)"/>
    <g id="guides"></g><g id="bars" fill="url(#bar)"></g><path d="M24 182H576" stroke="#99af99"/>
    <g id="ticks" class="axis"></g>
  </svg>
</section>
<div class="controls"><button id="low" data-hz="220" aria-pressed="false">220 Hz</button><button id="high" data-hz="880" aria-pressed="false">880 Hz</button><button id="stop" disabled data-i="stop">소리 끄기</button></div>
<footer><span id="state" role="status"></span></footer><p id="hint" data-i="hint">주파수 버튼을 누르면 작은 시험음이 납니다. 두 음을 번갈아 눌러 가장 높은 막대의 위치를 비교하세요.</p>
</main><script>
'use strict';
const language=new URLSearchParams(location.search).get('lang')||document.documentElement.lang;
const words={
 ko:{title:'두 음의 스펙트럼',kind:'주파수 분석',peak:'가장 강한 주파수',chart:'시험음의 주파수별 세기',desc:'왼쪽이 낮은 음, 오른쪽이 높은 음입니다. 막대 높이가 주파수 구간별 세기를 나타냅니다.',stop:'소리 끄기',ready:'소리 꺼짐',playing:'시험음 재생 중',hint:'주파수 버튼을 누르면 작은 시험음이 납니다. 두 음을 번갈아 눌러 가장 높은 막대의 위치를 비교하세요.',error:'이 브라우저에서 소리를 시작할 수 없습니다.'},
 en:{title:'Two tones, one spectrum',kind:'Frequency analysis',peak:'Peak frequency',chart:'Strength across frequency bands',desc:'Low frequencies are on the left and high frequencies on the right. Bar height measures the strength in each band.',stop:'Stop tone',ready:'Sound off',playing:'Tone playing',hint:'Press a frequency to hear a quiet test tone. Switch between the two and compare the position of the tallest bar.',error:'Audio could not start in this browser.'},
 es:{title:'El espectro de dos tonos',kind:'Análisis de frecuencias',peak:'Frecuencia dominante',chart:'Intensidad por banda de frecuencia',desc:'Las frecuencias graves aparecen a la izquierda y las agudas a la derecha. La altura indica la intensidad de cada banda.',stop:'Silenciar',ready:'Sonido apagado',playing:'Tono en reproducción',hint:'Pulsa una frecuencia para oír un tono suave. Alterna entre los dos y compara la posición de la barra más alta.',error:'No se pudo iniciar el audio en este navegador.'},
 'zh-Hans':{title:'两个音的频谱',kind:'频率分析',peak:'峰值频率',chart:'各频段的强度',desc:'左侧频率较低，右侧较高。柱高表示各频段的强度。',stop:'停止发声',ready:'声音已关闭',playing:'正在播放测试音',hint:'点按频率可听到轻柔的测试音。交替点按两个频率，观察最高柱的位置。',error:'当前浏览器无法启动音频。'}
};
const lang=Object.hasOwn(words,language)?language:'ko', t=words[lang];document.documentElement.lang=lang;document.title=t.title;document.getElementById('title').textContent=t.title;
for(const el of document.querySelectorAll('[data-i]'))el.textContent=t[el.dataset.i];
const buttons=[...document.querySelectorAll('[data-hz]')], stopButton=document.getElementById('stop'), status=document.getElementById('state'), peak=document.getElementById('peak');
const osReduce=matchMedia('(prefers-reduced-motion: reduce)');
function reduced(){return osReduce.matches||new URLSearchParams(location.search).get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')}
const count=52, low=80, high=2000, width=552, baseline=180, bars=[], heights=Array(count).fill(0);
function svg(tag,parent,attrs){const el=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const [k,v] of Object.entries(attrs))el.setAttribute(k,v);parent.append(el);return el}
function position(hz){return 24+width*Math.log(hz/low)/Math.log(high/low)}
for(const hz of [80,220,440,880,2000]){
  const x=position(hz);svg('line',document.getElementById('guides'),{x1:x,x2:x,y1:16,y2:180,class:'guide'});
  svg('text',document.getElementById('ticks'),{x,y:205,'text-anchor':hz===80?'start':hz===2000?'end':'middle'}).textContent=hz===2000?'2k Hz':hz;
}
for(let i=0;i<count;i++){bars.push(svg('rect',document.getElementById('bars'),{x:24+i*width/count+1,y:baseline-2,width:width/count-2,height:2,rx:1}));}
let audio, analyser, output, oscillator, spectrum, selected=0, version=0, frame=0, decayStart=0, lastRead=0, decay=[];
function showControls(){buttons.forEach(b=>b.setAttribute('aria-pressed',String(+b.dataset.hz===selected)));stopButton.disabled=!selected;status.textContent=selected?t.playing+' · '+selected+' Hz':t.ready;}
function setBar(i,v){heights[i]=v;const h=2+v*150;bars[i].setAttribute('y',(baseline-h).toFixed(2));bars[i].setAttribute('height',h.toFixed(2));}
function clearMeter(){peak.value='— Hz';peak.dataset.hz='0';}
function draw(time){
  if(selected && analyser){
    if(!reduced()||time-lastRead>=120||lastRead===0){
      analyser.getByteFrequencyData(spectrum);
      const step=audio.sampleRate/analyser.fftSize, start=Math.ceil(low/step),end=Math.min(spectrum.length-1,Math.floor(high/step));
      let best=start;
      for(let j=start+1;j<=end;j++)if(spectrum[j]>spectrum[best])best=j;
      if(spectrum[best]>4){const value=Math.round(best*step);peak.value=value+' Hz';peak.dataset.hz=String(value);}else clearMeter();
      for(let i=0;i<count;i++){
        const from=Math.ceil(low*(high/low)**(i/count)/step), until=Math.ceil(low*(high/low)**((i+1)/count)/step);
        let value=0;for(let j=from;j<until&&j<spectrum.length;j++)value=Math.max(value,spectrum[j]);setBar(i,value/255);
      }lastRead=time;
    }
  }else{
    const remaining=reduced()?0:Math.max(0,1-(time-decayStart)/340);for(let i=0;i<count;i++)setBar(i,(decay[i]||0)*remaining);
    if(!remaining){frame=0;return;}
  }frame=requestAnimationFrame(draw);
}
async function play(hz){
  const id=++version;
  try{
    if(!audio){const Context=window.AudioContext||window.webkitAudioContext;if(!Context)throw Error('audio');
      audio=new Context();analyser=audio.createAnalyser();analyser.fftSize=8192;analyser.minDecibels=-91;analyser.maxDecibels=-29;analyser.smoothingTimeConstant=.32;
      output=audio.createGain();output.gain.value=.035;output.connect(analyser);analyser.connect(audio.destination);spectrum=new Uint8Array(analyser.frequencyBinCount);
    }
    if(audio.state!=='running')await audio.resume();if(id!==version||document.hidden)return;
    if(!oscillator){oscillator=audio.createOscillator();oscillator.type='sine';oscillator.connect(output);oscillator.frequency.value=hz;oscillator.start();}
    else oscillator.frequency.setValueAtTime(hz,audio.currentTime);
    selected=hz;lastRead=0;showControls();if(!frame)frame=requestAnimationFrame(draw);
  }catch{if(id===version){stopTone();status.textContent=t.error;}}
}
function stopTone(){
  version++;if(oscillator){oscillator.stop();oscillator.disconnect();oscillator=null;}
  selected=0;clearMeter();showControls();decay=heights.slice();decayStart=performance.now();
  if(frame)cancelAnimationFrame(frame);frame=0;
  if(reduced()||document.hidden)heights.forEach((_,i)=>setBar(i,0));else frame=requestAnimationFrame(draw);
}
buttons.forEach(b=>b.addEventListener('click',()=>play(+b.dataset.hz)));stopButton.addEventListener('click',stopTone);
document.addEventListener('visibilitychange',()=>{if(document.hidden)stopTone()});
window.addEventListener('pagehide',()=>{stopTone();if(audio)audio.close().catch(()=>{});audio=null;});showControls();clearMeter();
</script></body></html>
```
