Duvrai
Duvrai

Reputation: 3458

Enable/disable simultaneous audio tracks in the browser

I want to play multiple audio tracks at the same time in sync and be able to enable or disable tracks programmatically while playing.

I tried putting multiple audio streams in one mp4 file and then set the enabled property of a track like this:

mySong.audioTracks[n].enabled

But that technique is currently only supported in IE and Safari.

Is this something that can be done with the Web Audio API which seems to have better browser support?

Upvotes: 1

Views: 443

Answers (2)

Raymond Toy
Raymond Toy

Reputation: 6048

For a possible WebAudio solution, assume you have your mp4 file decoded into an AudioBufferSource, s, with n channels.

Then:

var splitter = context.createSplitter(n);
s.connect(splitter);

for (k = 0; k < n; ++k) {
  gains[k] = context.createGain();
  spitter.connect(gains[k], k, 0);
  gains[k].connect(context.destination);
}

// To disable channel m:
gains[m].gain.value = 0;
// To re-enable channel m:
gains[m].gain.value = 1;

You can get fancier by having each channel fade in and fade out too.

Upvotes: 1

luc122c
luc122c

Reputation: 439

If you are using HTML5 Audio, you can use the .play() and .pause() commands as detailed in MDN's guide.

Let's say you have a page with five HTML5 Audio elements, each with the class .song1. If you are wanting to stop and start all tracks at the same time, you could assign buttons to run:

document.getElementsByClassName("song1").play();

and

document.getElementsByClassName("song1").pause();

If you are wanting to mute a track whilst the others continue to play, you can set it's volume to 0 programatically too:

getElementsByTagName("audio")[0].volume=0; <!-- Mute track 1 -->

or

getElementsByTagName("audio")[2].volume=0; <!-- Mute track 3 etc -->

Hope this helps!

Upvotes: 0

Related Questions