Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Preload Audio Files / Event?

I am preloading all my assets before I start a JS-based application doing:

assets = [....]; // files
$.each(assets,function(){
    var r = /.([^.]+)$/;
    var ext = r.exec(this); //get file type
    if (ext[1] == 'png'){
        var tmp = new Image();
    } else if (ext[1] == 'mp3'){
        var tmp = new Audio();
    }

    tmp.src = this;
    tmp.onload = function(){
        var i = assets.indexOf(this);
        assets.splice(i,1);
        if (!assets.length){
            console.log('all loaded');
            app.build();
        }
    }
});

This works fine when I have just pngs in my Array, yet when I add audio (mp3s) the DOM element gets created, yet it never fires an onload so the app never starts. I tried adding a tmp.load() already but it didn't make any difference - also I couldn't really find any comprehensive information on the web. Is this approach even possible? Does an Audio() even fire an appropriate event? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looking for media events, which says you could use e.g. loadeddata.

I'd like to address some other points:

  • Characters inside a regexp character group don't need escaping.
  • Why not use jQuery for creating the elements and binding the event handler?

I altered your code a little bit:

$.each(assets, function() {
    var r = /.([^.]+)$/,
        ext = r.exec(this), //get file type
        tmp = ext[1] === 'png'
                ? $("<img>")
                : $("<audio>"),
        eventName = ext[1] === 'png'
                    ? 'load'
                    : 'loadeddata';

    tmp
      .on(eventName, function() {
          var i = assets.indexOf(this);
          assets.splice(i, 1);

          if (!assets.length){
              console.log('all loaded');
              app.build();
          }
      })
      .attr("src", this); // only set after adding the load callback
                          // to avoid a possible race condition
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...