最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clone Audio object - Stack Overflow

programmeradmin2浏览0评论

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
  • var audio = new Audio("file.mp3");var audio2 = new Audio("file.mp3") – Musa Commented Jul 4, 2013 at 4:18
  • @Musa right, but is that slow? – MiJyn Commented Jul 4, 2013 at 4:35
  • Idon't know, do some benchmarks and see. Also there is var audio2 = audio.cloneNode(); – Musa Commented Jul 4, 2013 at 4:40
  • @MiJyn, If you mean slow as in having to download the file again, no. The browser will load it from cache. – Brad Commented Jul 4, 2013 at 4:42
  • @Brad, okay, thanks! That clarifies a lot – MiJyn Commented Jul 4, 2013 at 5:14
 |  Show 1 more comment

3 Answers 3

Reset to default 11

I 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])
发布评论

评论列表(0)

  1. 暂无评论