06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In code, this translates <strong>to</strong>:<br />

// If the volume is greater than one and we are not clapping, draw a rectangle<br />

if (vol > 0.5 & & !clapping) {<br />

// Trigger event!<br />

clapping = true; // We are now clapping!<br />

} else if (clapping & & vol < 0.25) { // If we are finished clapping<br />

clapping = false;<br />

}<br />

Here is the full example where one and only one rectangle appears per clap.<br />

Example 20-7: Sound events (double threshold) with Sonia<br />

// Import the Sonia library<br />

import pitaru.sonia_v2_9.*;<br />

float clapLevel = 0.5; // How loud is a clap<br />

float threshold = 0.25; // How quiet is silence<br />

boolean clapping = false;<br />

void setup() {<br />

size(200,200);<br />

Sonia.start(this); // Start Sonia engine.<br />

LiveInput.start(); // Start listening <strong>to</strong> the microphone<br />

smooth();<br />

background(255);<br />

}<br />

void draw() {<br />

// Get the overall volume (between 0 and 2.0)<br />

float vol = LiveInput.getLevel();<br />

// If the volume is greater than 0.5 and<br />

// we are not clapping, draw a rectangle<br />

if (vol > clapLevel & & !clapping) {<br />

stroke(0);<br />

fill(0,100);<br />

rect(random(width),random(height),vol*20,vol*20);<br />

clapping = true; // We are now clapping!<br />

// If we are finished clapping<br />

} else if (clapping & & vol < threshold) {<br />

clapping = false;<br />

}<br />

// Graph the overall volume<br />

// First draw a background strip<br />

noStroke();<br />

fill(200);<br />

rect(0,0,20,height);<br />

// Then draw a rectangle size according <strong>to</strong> volume<br />

fill(100);<br />

rect(0,height-vol*height/2,20,vol*height/2);<br />

fi g. 20.4<br />

Sound 395<br />

If the volume is greater<br />

than 1.0, and we were not<br />

previously clapping, then we<br />

are clapping!<br />

Otherwise, if we were just<br />

clapping and the volume<br />

level has gone down below<br />

0.25, then we are no longer<br />

clapping!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!