Skip to content

Language Settings

Measuring Amplitude

Analyze the amplitude of sound with p5.Amplitude.

*

Amplitude is the magnitude of vibration. Sound is vibration, so its amplitude is is closely related to volume / loudness.

*

The getLevel() method takes an array of amplitude values collected over a small period of time (1024 samples). Then it returns the Root Mean Square (RMS) of these values.

*

The original amplitude values for digital audio are between -1.0 and 1.0. But the RMS will always be positive, because it is squared. And, rather than use instantanous amplitude readings that are sampled at a rate of 44,100 times per second, the RMS is an average over time (1024 samples, in this case), which better represents how we hear amplitude.

To run this example locally, you will need the p5.sound library a sound file, and a running local server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let song, analyzer;
function preload() {
  song = loadSound('assets/lucky_dragons_-_power_melody.mp3');
}
function setup() {
  createCanvas(710, 200);
  song.loop();
  // create a new Amplitude analyzer
  analyzer = new p5.Amplitude();
  // Patch the input to an volume analyzer
  analyzer.setInput(song);
}
function draw() {
  background(255);
  // Get the average (root mean square) amplitude
  let rms = analyzer.getLevel();
  fill(127);
  stroke(0);
  // Draw an ellipse with size based on volume
  ellipse(width / 2, height / 2, 10 + rms * 200, 10 + rms * 200);
}
X

creative commons license