Jamie
Jamie

Reputation: 491

How can I prevent simultaneously playing js audio from interfering with one another

I have some javascript that plays audio from several .wav files using the standard audio commands e.g.:

var audio = new Audio('audio_file.wav');
audio.play();

When the user plays two sounds in quick succession, the sounds start to interfere with each other and get distorted/strange sounding. Notably, when I just play the files in a media player simultaneously, this does not happen - it's simply the two sounds playing at the same time without any distortion. Is this a known thing that happens when playing audio in js, and is there are way to solve it so that multiple sounds playing simultaneously do not cause distortions in one another? Any help would be great!

Upvotes: 0

Views: 325

Answers (1)

Brad
Brad

Reputation: 163291

You need to reduce the volume of the sound you're playing.

Multiple sounds are mixing together, periodically "clipping"... pushing the sample values beyond what can be represented in your system's audio sample format.

Try something like this:

audio.volume = 0.6;

Now, if you have times where you're usually only playing one sound at once, but some other times where you need multiple, simply reducing the volume may not be desirable, as playback might be too quiet.

For these times, you might consider switching to the Web Audio API and using a compressor:

https://developer.mozilla.org/en-US/docs/Web/API/DynamicsCompressorNode

This "squeezes" the loud parts and the quiet parts so that they all sound a bit similar, allowing you to reduce the output levels while still sounding loud when possible.

Upvotes: 2

Related Questions