I am aware of how to clone an object, but I'm wondering, how do I clone an audio object? Should I clone it differently than I would clone an object?
To "illustrate" what I mean:
var audio = new Audio("file.mp3");
var audio2 = $.extend({}, audio); // Clones `audio`
Is this the correct way to do this?
Reason why I'm asking this is that I want to be able to play the same sound multiple times simultaneously.
I am aware of how to clone an object, but I'm wondering, how do I clone an audio object? Should I clone it differently than I would clone an object?
To "illustrate" what I mean:
var audio = new Audio("file.mp3");
var audio2 = $.extend({}, audio); // Clones `audio`
Is this the correct way to do this?
Reason why I'm asking this is that I want to be able to play the same sound multiple times simultaneously.
Share Improve this question edited Jul 4, 2013 at 4:40 MiJyn asked Jul 4, 2013 at 4:15 MiJynMiJyn 5,8677 gold badges39 silver badges66 bronze badges 6 | Show 1 more comment3 Answers
Reset to default 11I had exactly the same predicament as originally raised. The following worked perfectly well for me :
var audio2 = audio.cloneNode();
This question is ancient in javascript years. I think your code is (was) downloading the audio again and that was the cause of your delay. If you grab the audio file once and store it in a blob, you can then use that blob as the source for new audio events.
let fileBlob;
fetch("file.mp3")
.then(function(response) {return response.blob()})
.then(function(blob) {
fileBlob=URL.createObjectURL(blob);
new Audio(fileBlob); // forces a request for the blob
});
...
new Audio(fileBlob).play() // fetches the audio file from the blob.
You can also do a lot of stuff with the web audio api, but it has a slightly steeper learning curve.
#1
let audio_2 = audio_1.slice()
or
#2
let audio_2 = new Blob([audio_1])
var audio = new Audio("file.mp3");var audio2 = new Audio("file.mp3")
– Musa Commented Jul 4, 2013 at 4:18var audio2 = audio.cloneNode();
– Musa Commented Jul 4, 2013 at 4:40