js mode HTML5 audio example

This commit is contained in:
fjenett
2011-06-12 11:57:28 +00:00
parent c09a266805
commit 1d70588bb0
4 changed files with 171 additions and 0 deletions

View File

@@ -0,0 +1,130 @@
/**
* Blobbbs. <br />
*
* <audio>
* <source src="BD.wav" />
* <source src="BD.mp3" />
* </audio>
*/
Ball[] balls;
float maxSpeed = 0.5;
Audio audio;
void setup ()
{
size( 400, 300 );
}
void draw ()
{
background(75);
if ( balls != null )
{
for ( int i = 0; i < balls.length; i++ )
{
balls[i].update();
balls[i].draw();
}
}
}
void newAudio ( Audio a )
{
if ( audio == null )
{
audio = a;
balls = new Ball[10];
for ( int i = 0; i < balls.length; i++ )
{
balls[i] = new Ball();
}
}
}
class Ball
{
float px,py;
float dx,dy;
float rad;
float col;
float hitness;
Ball ()
{
rad = random(2,20);
px = rad + random(width-2*rad);
py = rad + random(height-2*rad);
dx = random(-maxSpeed,maxSpeed);
dy = random(-maxSpeed,maxSpeed);
colorMode(HSB);
col = color(random(255),200,150);
colorMode(RGB);
hitness = 50;
}
void update ()
{
px += dx;
py += dy;
hitness -= hitness/10;
if ( px-rad <= 0 || px+rad >= width )
{
dx *= -1;
playSound();
hitness = 10;
}
if ( py-rad <= 0 || py+rad >= height )
{
dy *= -1;
playSound();
hitness = 10;
}
}
void playSound ()
{
if ( audio != null )
{
audio.pause();
audio.currentTime = 0;
audio.play();
}
}
void draw ()
{
strokeWeight( hitness );
stroke(200);
fill(col);
ellipse( px, py, rad*2, rad*2 );
}
}
/* let Processing know about the HTMLAudioElement */
interface Audio
{
boolean muted;
float volume;
boolean loop;
boolean paused;
boolean ended;
String currentSrc;
float duration;
float currentTime;
void play();
void pause();
Audio cloneNode( boolean deep ); /*DOM*/
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,41 @@
window.onload = function () {
var audioNode = document.getElementsByTagName("audio")[0];
function tryFindSketch () {
var sketch = Processing.instances[0];
if ( sketch == undefined )
return setTimeout(tryFindSketch,200); // retry
sketch.newAudio( audioNode );
}
addEvent(audioNode, 'canplaythrough', function () {
tryFindSketch();
});
}
// http://html5demos.com/
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();