# 等功率立体声声像

同一单声道信号以不同增益送往左右声道。居中时左右增益各约 0.707；在任何位置，两路增益的平方和均为 1。

## 试一试

依次选左、中央、右并观察电平表。播放测试音，在声音持续期间移动声像。

## 交互细节

在 −1 和 +1 时只有一侧收到信号；居中时两侧相等。330 赫兹的测试音持续约 0.8 秒。

## 各平台的操作方式

- iOS · 拖动声像滑块或轻点位置按钮，轻点播放测试音即可试听。
- Android · 拖动声像滑块或轻点位置按钮，轻点播放测试音即可试听。
- PC · 用 Tab 选中声像滑块并用方向键调节。选中播放测试音后按回车。

## 适用场景

适合演示立体声调音台的声像旋钮如何分配单声道信号。

## 实现要求

> 为单声道测试音制作等功率声像控制，显示左右增益及其平方和，只在用户按下按钮时播放短音。

## 来源与致谢

[W3C · StereoPannerNode panning](<https://www.w3.org/TR/webaudio-1.1/#stereopanner-algorithm>)

## 独立 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{font:15px/1.4 system-ui,"Malgun Gothic",sans-serif;color:#322c46;background:#edeaf1;color-scheme:light;--accent:#654480}
body{margin:0;padding:clamp(10px,3vw,26px);min-height:100svh;display:grid;align-content:center}
main{width:min(100%,740px);margin:auto}
header,.readout{display:flex;align-items:baseline;justify-content:space-between;gap:8px 18px;flex-wrap:wrap}
header{margin:0 0 9px}h1{margin:0;font-size:clamp(20px,4vw,33px);letter-spacing:-.05em;line-height:1.12}
header small{font:650 12px/1.3 ui-monospace,monospace}
figure{margin:0}canvas{display:block;width:100%;height:auto;aspect-ratio:700/250;border-radius:7px;background:#232238}
.readout{padding:6px 0;font:650 clamp(11px,1.8vw,14px)/1.35 ui-monospace,monospace}
.controls{display:flex;gap:6px 9px;align-items:center;flex-wrap:wrap;border-top:1px solid currentColor;padding-top:8px}
button{min-height:35px;padding:7px 12px;border:1px solid currentColor;background:transparent;color:inherit;border-radius:5px;cursor:pointer;font:650 13px/1.2 system-ui,sans-serif}
button:active,button[aria-pressed="true"]{color:white;background:var(--accent);border-color:var(--accent)}
button:focus-visible,input:focus-visible{outline:3px solid var(--accent);outline-offset:3px}
label{display:flex;align-items:center;gap:7px;flex:1 1 124px;min-width:0;font-size:12px;font-weight:650}
label span{flex:none;white-space:nowrap}
input[type="range"]{accent-color:var(--accent);flex:1 1 70px;min-width:55px;width:auto;margin:0}
@media(max-width:450px){header small{font-size:10px}.readout{gap:3px 7px}button{min-height:36px;padding:6px 9px}.controls{gap:5px}.controls label{flex-basis:100%}}
</style></head>
<body><main><header><h1 data-t="title"></h1><small data-t="method"></small></header>
<figure><canvas id="board" width="700" height="250" role="img"></canvas>
<figcaption class="readout"><span id="status"></span><output id="reading"></output></figcaption></figure>
<div class="controls"><button id="left" data-t="left"></button><button id="center" data-t="center"></button><button id="right" data-t="right"></button><button id="listen" data-t="listen"></button><label><span data-t="pan"></span><input id="pan" type="range" min="-100" max="100" step="1" value="0"></label></div></main>
<script>
'use strict';
const words={
 "title": [
  "두 채널 사이의 소리",
  "Between two speakers",
  "Entre dos altavoces",
  "两个声道之间"
 ],
 "method": [
  "등전력 스테레오 패닝",
  "Equal-power stereo pan",
  "Panorámica de potencia constante",
  "等功率立体声声像"
 ],
 "description": [
  "왼쪽과 오른쪽의 신호 크기와 같은 소리의 스테레오 위치",
  "Left and right gain meters and the position of one mono tone",
  "Ganancias izquierda y derecha y posición de un tono mono",
  "左右声道增益表以及单声道音源的声像位置"
 ],
 "left": [
  "왼쪽",
  "Left",
  "Izquierda",
  "左"
 ],
 "right": [
  "오른쪽",
  "Right",
  "Derecha",
  "右"
 ],
 "center": [
  "중앙",
  "Center",
  "Centro",
  "中央"
 ],
 "pan": [
  "위치",
  "Pan",
  "Posición",
  "声像"
 ],
 "listen": [
  "시험음 듣기",
  "Play tone",
  "Escuchar tono",
  "播放测试音"
 ],
 "idle": [
  "모노 입력",
  "Mono input",
  "Entrada mono",
  "单声道输入"
 ],
 "playing": [
  "시험음 재생 중",
  "Tone playing",
  "Tono en curso",
  "正在播放"
 ],
 "silent": [
  "오디오 출력 사용 불가",
  "Audio output unavailable",
  "Salida de audio no disponible",
  "音频输出不可用"
 ]
};
const languages=["ko","en","es","zh-Hans"];
const params=new URLSearchParams(location.search);
const preferred=params.get('lang')||document.documentElement.lang;
const code=languages.includes(preferred)?preferred:'ko';
const tr=k=>words[k][languages.indexOf(code)];
const by=id=>document.getElementById(id);
document.documentElement.lang=code;
document.title=tr('title');
document.querySelectorAll('[data-t]').forEach(el=>el.textContent=tr(el.dataset.t));
const board=by('board'),ctx=board.getContext('2d');
board.setAttribute('aria-label',tr('description'));
const reduced=()=>params.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||matchMedia('(prefers-reduced-motion: reduce)').matches;
let animation=0;
function animate(from,to,duration,render){
  cancelAnimationFrame(animation);
  if(reduced()||from===to){render(to);return;}
  const start=performance.now();
  function frame(now){
    const fraction=Math.min(1,(now-start)/duration);
    render(from+(to-from)*fraction);
    if(fraction<1)animation=requestAnimationFrame(frame);
  }
  animation=requestAnimationFrame(frame);
}

let current=0, audio, panner, voice, toneSerial=0;
function meter(x,gain,color,letter){
 ctx.fillStyle='#eee7fb';ctx.font='500 33px Georgia,serif';ctx.fillText(letter,x,53);
 for(let i=0;i<20;i++){
   const y=208-i*7.1;
   ctx.fillStyle=(i+.5)/20<=gain?color:'#414055';ctx.fillRect(x,y,74,4.4);
 }
 ctx.font='600 15px ui-monospace,monospace';ctx.fillStyle=color;ctx.fillText(gain.toFixed(3),x,234);
}
function show(value){
 current=Math.max(-100,Math.min(100,value));
 const p=current/100, angle=(p+1)*Math.PI/4, left=Math.cos(angle),right=Math.sin(angle);
 ctx.fillStyle='#232238';ctx.fillRect(0,0,700,250);
 meter(46,left,'#8ae2c9','L');meter(582,right,'#ffac94','R');
 const cx=350,cy=209,r=149;ctx.lineWidth=2;ctx.strokeStyle='#8d87a6';ctx.beginPath();ctx.arc(cx,cy,r,Math.PI,2*Math.PI);ctx.stroke();
 for(let i=0;i<=16;i++){
   const a=Math.PI+i*Math.PI/16;
   ctx.beginPath();ctx.moveTo(cx+(r-7)*Math.cos(a),cy+(r-7)*Math.sin(a));
   ctx.lineTo(cx+(r+3)*Math.cos(a),cy+(r+3)*Math.sin(a));ctx.stroke();
 }
 const bearing=Math.PI+(p+1)*Math.PI/2, x=cx+r*Math.cos(bearing), y=cy+r*Math.sin(bearing);
 ctx.beginPath();ctx.moveTo(cx,cy);ctx.lineTo(x,y);ctx.lineWidth=3;ctx.strokeStyle='#e8d5f6';ctx.stroke();
 ctx.beginPath();ctx.arc(x,y,10,0,2*Math.PI);ctx.fillStyle='#f6dcaf';ctx.fill();
 ctx.beginPath();ctx.arc(cx,cy,9,0,2*Math.PI);ctx.fillStyle='#cfc4df';ctx.fill();
 by('pan').value=Math.round(current);by('reading').textContent='L² + R² = '+(left*left+right*right).toFixed(3);
 board.dataset.pan=p.toFixed(3);board.dataset.left=left.toFixed(6);board.dataset.right=right.toFixed(6);
 for(const [id,target] of [['left',-100],['center',0],['right',100]])by(id).setAttribute('aria-pressed',String(current===target));
 if(panner)panner.pan.setValueAtTime(p,audio.currentTime);
}
for(const [id,v] of [['left',-100],['center',0],['right',100]])by(id).onclick=()=>animate(current,v,420,show);
by('pan').oninput=e=>{cancelAnimationFrame(animation);show(+e.target.value);};
by('listen').onclick=async()=>{
  const serial=++toneSerial;
  try{
    audio??=new (window.AudioContext||window.webkitAudioContext)();
    if(!panner){panner=audio.createStereoPanner();panner.connect(audio.destination);}
    await audio.resume();if(serial!==toneSerial)return;
    if(voice){try{voice.stop();}catch{}}
    const tone=audio.createOscillator(),gain=audio.createGain(),t=audio.currentTime;
    voice=tone;tone.frequency.value=330;gain.gain.setValueAtTime(0,t);gain.gain.linearRampToValueAtTime(.09,t+.02);
    gain.gain.setValueAtTime(.09,t+.75);gain.gain.linearRampToValueAtTime(0,t+.82);
    panner.pan.setValueAtTime(current/100,t);tone.connect(gain).connect(panner);
    by('status').textContent=tr('playing');board.dataset.tone='playing';
    tone.onended=()=>{gain.disconnect();tone.disconnect();if(voice===tone){voice=null;board.dataset.tone='idle';by('status').textContent=tr('idle');}};
    tone.start(t);tone.stop(t+.83);
  }catch{by('status').textContent=tr('silent');board.dataset.tone='unavailable';}
};
by('status').textContent=tr('idle');board.dataset.tone='idle';show(0);
</script></body></html>
```
