## Billiard simulation–part 7: sound

June 15, 2013 at 11:18 AM

Another way to make the simulation a bit more realistic is to produce some sound when balls hit each other and when they hit the side of the table.

Playing a sound in the browser turns out to be super-easy – create ‘Audio’ objects loading sound files:

  private audioBallBall = new Audio("sounds/ball-ball.mp3");
private audioBallSide = new Audio("sounds/ball-side.mp3");

and play them in the loop that process the collisions:

      // Compute the new velocities after the collisions
for (var i = 0; i < firstCollisions.collisions.length; i++) {
var collision = firstCollisions.collisions[i];
switch (collision.type) {
case "x":
this.audioBallSide.volume = Math.min(this.maxSpeed, Math.abs(collision.b1.v)) / this.maxSpeed;
this.audioBallSide.play();
collision.b1.v = -collision.b1.v * this.parameters.sideRestitution;
break;
case "y":
this.audioBallSide.volume = Math.min(this.maxSpeed, Math.abs(collision.b1.w)) / this.maxSpeed;
this.audioBallSide.play();
collision.b1.w = -collision.b1.w * this.parameters.sideRestitution;
break;
case "b":
var dx = (collision.b1.x - collision.b2.x);
var dy = (collision.b1.y - collision.b2.y);
var relativeSpeed = Math.abs((collision.b1.v - collision.b2.v) * dx + (collision.b1.w - collision.b2.w) * dy) / Math.sqrt(dx*dx + dy*dy);
this.audioBallBall.volume = Math.min(this.maxSpeed, relativeSpeed) / this.maxSpeed;
this.audioBallBall.play();
collision.b1.collide(collision.b2, this.parameters.ballRestitution);
break;
}
}

The volume is adjusted to decrease as the collision speed decreases, with 100% volume corresponding to some (rather arbitrary) maximum speed. I did not investigate the actual physics – I suspect that the sound volume does not simply decrease linearly with the speed, but it sounds good enough.

The audio files are loaded asynchronously by the browser, so in theory they should be played only after receiving a notification that loading completed (see here for example), but being very small file this is not really necessary.

I recorded myself the two different sounds used for ball-ball and ball-side collisions – hitting two different surfaces with a pen, not very realistic but good enough for now (probably the title of this post should be ‘good enough’). I used Audacity to record the sound and cut them – I didn’t do any other editing.

There are libraries of sound effects that can be bought quite cheaply, including billiard sound – see this for example, but they appear to be more complex sounds, not suitable for just a single impact.

UPDATE

The code above contained a bug in the computation of the relative speed for ball-ball collisions, now fixed.

Posted in: Programming

Tags: , ,