For the needs of my game I need to have 2D sound. That means, the emmiter should be positioned somewhere on a 2D plane. How do I achieve this effect in Javascript? Do I need to use a special sound format or can I control the volume on the speakers?
I think I can get to the point where I have 2 volumes for each speaker, but I am clueless as how to apply different volumes for the same sound in Javascript.
An article describing exactly this including a demo can be found here.
To prevent link rot I will be quoting the most relevant parts below
Luckily, Web Audio API comes with built-in hardware accelerated positional audio features that are quite straight forward to use.
The core idea is demonstrated in the code below:
PositionSample.prototype.changePosition = function(position) {
// Position coordinates are in normalized canvas coordinates
// with -0.5 < x, y < 0.5
if (position) {
if (!this.isPlaying) {
this.play();
}
var mul = 2;
var x = position.x / this.size.width;
var y = -position.y / this.size.height;
this.panner.setPosition(x * mul, y * mul, -0.5);
} else {
this.stop();
}
};
The full source code of the working demo in the first link above can be found here.
Offtopic: I considered rewriting the quoted article by hand as a custom answer here, but that seemed relatively pointless as the article is already more than clear enough and doing double work seems pointless
Compatibility wise, only a combination of flash and the previously mentioned code gives a true cross-browser positioning/panning audio solution (as flash is not available on certain mobile devices). Ideally I would advise against use of the audio API if this can be circumvented as it's not unlikely that things will change in the specification, thus possibly breaking your code (+ it's not unlikely for this not to work either way on mobile devices). The only scenario where using the more advanced web audio api's makes sense is if you are expecting to work at least another 6 to 18 months on your game (as that's the likely time it will take for the implementations to even stabalize to a usable point).
We've used SoundManager2 at work, at it was a really easy turn-key solutions and well documented API.
http://www.schillmania.com/projects/soundmanager2/
Example:
soundManager.createSound({
id:'mySound1',
url:'../mpc/audio/CHINA_1.mp3'
});
soundManager.play('mySound1');
BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With