4

The usual way of creating an audio player in JavaScript

var a = new Audio();
a.src = "test.mp3";

assumes the audio data is owned by the Audio object. What is the proper way to load audio data separately, and then create audio players which would play that existing data? One use-case is when you want to play the same sound simultaneously by multiple players, e.g. to create an echo effect. I would assume that to create another player using same data one can just do

var b = new Audio();
b.src = a.src;

but I wonder whether this is the best way to do it... and if it is, whether one would have to wait for loadeddata/canplaythrough events on b given those events had already fired on a.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
dragonroot
  • 5,653
  • 3
  • 38
  • 63

2 Answers2

5

Since Audio is a regular DOM element you can use cloneNode() method to create and play the same sound.

// Create your audio and clone
var myAudio = new Audio('my.mp3');
var myClonedAudio = myAudio.cloneNode();

// Play them simultaneously
myAudio.play();
myClonedAudio.play();
Semra
  • 2,787
  • 28
  • 26
-1

For playing multiple sounds at once you have to need to make 2 audio objects. Otherwise you can play the sound after the "ended" event like:

obj.addEventListener('ended', function() 
{
    obj.play();
}.bind(this, obj), false);

If you want multiple sounds at once, use a class for playing sounds, or music - which supports multiple channels.

Oh yes, to can play the sound, dont forget to add it, to the body:

var audioTag     = new Audio('');
document.body.appendChild(audioTag);
audioTag.src    =  name;

If you want such an audio-class, ask me (comment ;)

MrFischer
  • 117
  • 1
  • 4