capture sound

p5.js gives us the ability to capture microphone sound from our computers.

In order to do that we use the constructor  new p5.AudioIn() function. 

To turn the microphone on we use the start() function and to turn it off we use the stop() function.

Moreover, we can get the volume levels of our microphone by using the getLevel() function. This functions returns values from 0.0 to 1.0.

Example 

Here is an example code where we capture microphone sound and draw an ellipse which will be changing size according to sound level:

// create variable to hold microphone inpute
let myMic;
function setup() {
  createCanvas(windowWidth, windowHeight);
  // capture microphone sound
  myMic = new p5.AudioIn();
  // turn on microphone
  myMic.start();
}
function draw() {
  background(123,23,45);
  // get the audio level
  let myMicLevel = myMic.getLevel();
  // create a sketch which will be changing according to audio level
  // we multiply the level by 1000 since the values it returns are very small
  ellipse(width / 2, height / 2, myMicLevel * 1000, myMicLevel * 1000);
}

You can see the result of the above code here

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex1033.js
  3. Open the file ex812.html in your editor and save it as ex1033.html
  4. In the ex1033.html file, update the link to ex1033.js  from exersice812.js
  5. Go to the index.html file and create, under Module 10, a link to the ex1033.html  file with the title "capture sound".

Modify the ex1033.jsfile and create an ellipse which will change color according to microphone volume. Moreover, if the volume is greater or equal to 100, keep its y position constant and change its x position according to volume. Else, change its y position. You can see here an example.

Answer:

/// create variable to hold microphone inpute
let myMic;
// create variables for RGB
let r,g,b;
function setup() {
  createCanvas(windowWidth, windowHeight);
  background(123,23,45);
  // capture microphone sound
  myMic = new p5.AudioIn();
  // turn on microphone
  myMic.start();

}
function draw() {

  // get the audio level
  let myMicLevel = myMic.getLevel();
  // change ellipse fill according to microphone volume
  r = myMicLevel * 2000;
  g = myMicLevel * 1000;
  b = myMicLevel * 800;
  fill (r,g,b,50);
  // create a sketch which will be changing according to audio level
  // if the volume is greater or equal to 100
  if (myMicLevel * 8000>=100){
    // change its x position
    ellipse((200+(myMicLevel * 8000)), 200, 200);
  }
  else {
    // else change its y position
    ellipse(200, (200+(myMicLevel * 8000)), 200); 
  }
}

Do a Git commit with the message "capture sound".