Skip to main content
rule CX Codex

audio-spatial — Claude Code rule: what it does, how to install

The audio-spatial rule for Claude Code provides Three.js 3D audio patterns for source positioning, distance falloff, and response to user interaction.

MIT ★ 4,719 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/audio-spatial.md
Open on GitHub

What audio-spatial does

The rule provides implementation patterns for the Three.js audio system. It covers attaching an AudioListener to the scene camera, configuring non-positional background audio, and binding PositionalAudio to 3D meshes. Settings include distance rolloff models (linear, inverse, exponential), HRTF panning, and directional cones.

It also details buffer loading with AudioLoader, spectrum analysis with AudioAnalyser, and buffer reuse for repeated sound effects.

Browser autoplay restrictions will silence audio without explicit user interaction: listener.context.resume() must be triggered from a gesture event handler.

What it helps with

  • attach 3D positional audio to scene meshes in Three.js
  • configure distance rolloff and directional cones for sound sources
  • handle browser autoplay restrictions by resuming AudioContext on user interaction
  • extract frequency data using AudioAnalyser for visual effects

Example prompts for the agent

  • Add a positional sound to the player mesh with inverse distance falloff
  • Implement user gesture handling to resume AudioContext before playing music
  • Create a frequency-based mesh scaling effect using AudioAnalyser

How to install audio-spatial

Manually: put the files in place

.claude/rules/audio-spatial.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about audio-spatial

How to install audio-spatial in Claude Code?

Place the rule file at .claude/rules/audio-spatial.md in your project repository.

What does audio-spatial do?

It provides guidelines and code examples for Three.js audio components, covering PositionalAudio, distance rolloff, and sound cleanup.

How does the rule handle browser autoplay policies?

It includes code patterns to resume listener.context and start playback only after a user gesture event, such as a button click.

Source text

audio-spatial.md · MIT
# Spatial Audio

Three.js audio system for 3D positional sound.

## Components

```javascript
import * as THREE from 'three';

// AudioListener - represents user position (attach to camera)
const listener = new THREE.AudioListener();
camera.add(listener);

// Audio - non-positional (background music)
const sound = new THREE.Audio(listener);

// PositionalAudio - 3D spatial sound
const positionalSound = new THREE.PositionalAudio(listener);
mesh.add(positionalSound);
```

## Loading Audio

```javascript
const audioLoader = new THREE.AudioLoader();
audioLoader.load('sound.mp3', (buffer) => {
  sound.setBuffer(buffer);
  sound.setLoop(true);
  sound.setVolume(0.5);
  sound.play();
});
```

## PositionalAudio Configuration

```javascript
const positionalAudio = new THREE.PositionalAudio(listener);

// Reference distance (max volume distance)
positionalAudio.setRefDistance(1);

// Maximum distance
positionalAudio.setMaxDistance(100);

// Rolloff model: 'linear', 'inverse', 'exponential'
positionalAudio.setRolloffFactor(1);
positionalAudio.setDistanceModel('inverse');

// Panning model: 'HRTF' (realistic) or 'equalpower'
positionalAudio.panner.panningModel = 'HRTF';

// Directionality (cone)
positionalAudio.setDirectionalCone(180, 230, 0.1);
// innerAngle, outerAngle, outerGain
```

## Distance Models

| Model | Behavior |
|-------|----------|
| `linear` | Linear decrease from ref to max distance |
| `inverse` | Inverse relationship (realistic) |
| `exponential` | Exponential falloff |

## Audio Controls

```javascript
// Play/pause
sound.play();
sound.pause();
sound.stop();

// Volume
sound.setVolume(0.5);  // 0.0 to 1.0

// Playback rate
sound.setPlaybackRate(1.5);

// Loop
sound.setLoop(true);

// Check state
if (sound.isPlaying) { }

// Duration
const duration = sound.buffer.duration;

// Current time
sound.offset; // read
```

## Audio Analyzer

```javascript
const analyser = new THREE.AudioAnalyser(sound, 32);

function animate() {
  const data = analyser.getAverageFrequency();
  // Use data for visualizations
  mesh.scale.setScalar(1 + data / 256);
}
```

## Multiple Audio Sources

```javascript
// Background music
const bgMusic = new THREE.Audio(listener);
audioLoader.load('music.mp3', (buffer) => {
  bgMusic.setBuffer(buffer);
  bgMusic.setLoop(true);
  bgMusic.setVolume(0.3);
});

// Spatial sounds on objects
objects.forEach((obj, i) => {
  const sound = new THREE.PositionalAudio(listener);
  audioLoader.load(`sound${i}.mp3`, (buffer) => {
    sound.setBuffer(buffer);
    sound.setRefDistance(5);
    sound.setLoop(true);
  });
  obj.add(sound);
});
```

## User Gesture Requirement

Audio requires user interaction to start (browser policy):

```javascript
const startButton = document.getElementById('start');
startButton.addEventListener('click', () => {
  // Resume AudioContext
  if (listener.context.state === 'suspended') {
    listener.context.resume();
  }
  sound.play();
  startButton.style.display = 'none';
});
```

## Best Practices

1. **HRTF**: Use `panningModel: 'HRTF'` for realistic 3D audio (best with headphones)

2. **User Gesture**: Always require user interaction before playing audio

3. **Dispose**: Call `audio.disconnect()` when removing sounds
   ```javascript
   sound.stop();
   sound.disconnect();
   ```

4. **Mobile**: Audio consumes significant battery on mobile devices

5. **Buffer Reuse**: Reuse audio buffers for repeated sounds
   ```javascript
   const sharedBuffer = await loadBuffer('shoot.mp3');

   function playShot(position) {
     const sound = new THREE.PositionalAudio(listener);
     sound.setBuffer(sharedBuffer);
     sound.position.copy(position);
     scene.add(sound);
     sound.play();
     sound.onEnded = () => {
       scene.remove(sound);
       sound.disconnect();
     };
   }
   ```

6. **Volume Levels**: Keep sound effects around 0.3-0.7, music around 0.2-0.4

7. **Ref Distance**: Set refDistance to the size of the emitting object

## Audio Formats

| Format | Browser Support | Notes |
|--------|-----------------|-------|
| MP3 | All | Good compression, universal |
| OGG | Chrome, Firefox | Better quality at same size |
| WAV | All | Uncompressed, large files |
| AAC | All | Good for music |

## References

- [Three.js Audio](https://threejs.org/docs/#api/en/audio/Audio)
- [Three.js PositionalAudio](https://threejs.org/docs/#api/en/audio/PositionalAudio)
- [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)

© zebbern · MIT · zebbern/claude-code-guide

Similar IDE rules

All IDE rules for Game dev and 3D: Unity, Unreal, Godot, Blender →

From the same set86

The whole set →
timeline-builder timeline-builder is a Claude Code skill that turns JSON event data into interactive HTML timelines with vertical, horizontal, or dual-side layouts. It covers project milestones, release histories, and resumes. CX Codex +1 ★ 4,719repo stars loading-suspense loading-suspense — a rule that keeps async React Three Fiber components inside Suspense, so a model still downloading doesn't leave the canvas blank. CX Codex +1 ★ 4,719repo stars lighting-shadows-advanced The lighting-shadows-advanced rule covers lighting and shadow settings in Three.js with rendering cost in mind. Use it when tuning a scene with several lights or shadow maps. CX Codex +1 ★ 4,719repo stars migration-checklist migration-checklist teaches the agent how to migrate code when Three.js updates. Lists breaking changes from r125 onwards and current import paths. CX Codex +1 ★ 4,719repo stars debug-devtools The debug-devtools rule guides an agent through adding diagnostics for Three.js performance, scene parameters, and WebGL context loss. Use it when tracking down a rendering bottleneck or inspecting a scene. CX Codex +1 ★ 4,719repo stars tsl-post-processing A reference rule for TSL post-processing in Three.js: chain effects onto postProcessing.outputNode instead of stacking EffectComposer passes. CX Codex +1 ★ 4,719repo stars tsl-compute-shaders tsl-compute-shaders guides the agent in writing WebGPU compute shaders with Three.js TSL for GPGPU tasks like particle systems and physics. CX Codex +1 ★ 4,719repo stars animation-system animation-system — a practical guide to Three.js animation, from playing and blending clips to morph targets and bones. Useful when building scenes with animated models. CX Codex +1 ★ 4,719repo stars

Project sponsors

Companies that keep this analytics open