Processing is not distributed with sound features built in, but you can use sound by installing a library. The Sound libraries need to be downloaded through the Library Manager. go to the "Sketch" menu and select "Add Library..." from the "Import Library..." submenu.
Use the search feature to find and install the "minim" sound library.
http://code.compartmental.net/tools/minim/quickstart/
...
language | java |
---|---|
title | sound code |
linenumbers | true |
...
p5.sound extends p5 with Web Audio functionality including audio input, playback, analysis and synthesis. In order to work with audio you need to download a javascript library here. The p5.SoundFile may not be available immediately because it loads the file information asynchronously.
Link to online demo
Code Block | ||
---|---|---|
| ||
let sound1; let sound2; function preload() { soundFormats('mp3', 'ogg'); sound1 = loadSound('doorbell.mp3'); sound2 = loadSound('cowbell.mp3'); } function setup() { sizecreateCanvas(600, 300); } // soundfunction initdraw() { minim = new Minim(thisbackground(100); sound1 = minim.loadSample("soundFile1.mp3"noStroke(); player = minim.loadFile("soundFile2.mp3"fill (255); } void draw() { //circle 1 background(100ellipse(400, height/2, 40, 40); noStroke(); fill(255fill (125); ellipse(200, height/2, 40, 40); } function mousePressed() { //circle 21 if (player.isPlaying(overCircle(200, height/2, 40)) { fillprint(255, 0, 0"circle 1"); doorBell(); } else {//circle 2 if fill(255); }(overCircle(400, height/2, 40)) { ellipseprint(400,"circle height/2, 40, 402"); cowBell(); }; } voidfunction mousePressed(overCircle( x, y, diameter) { //check if mouse is over the circle 1 if (overCircle(200dist(x, y, height/2mouseX, 40mouseY) <= diameter) { return true; println("circle 1"); sound1.trigger(); fill(255, 0, 0); ellipse(200, height/2, 40, 40); fill(255} else { return false; } } function doorBell() { //toggle sound on and off if (sound1.isPlaying() ) { sound1.stop(); } else { sound1.play(); sound2.stop(); } } function cowBell() { //circle 2toggle sound on and off if (overCircle(400, height/2, 40))sound2.isPlaying() ) { println("circle 2" sound2.stop(); } jukeBoxelse { sound2.play(); sound1.stop(); } } boolean overCircle(int x, int y, int diameter) { //check if mouse is over the circle if (dist(x, y, mouseX, mouseY) <= diameter) { return true; } else { return false; } } void jukeBox() { //toggle sound on and off if ( playersound1.isPlaying() ) { playersound1.pause(); } else { playersound1.play(); } // if the player reaches the end of the file, // it must be rewound toplay the startfile again before being replayed. if ( playersound1.positiononEnded() == player.length() ) { player.rewind(); player.sound1.play(); } } |
Download the source files:
...