0

I've got a page with a few <audio> elements in it. I get them in an array/collection/whatever, and want to listed for the "ended" event so as to try and auto play the next one. I'm stuck. How to I id the next song to .play() it? I think I'm about to blow my computer up.

Here's what I have...

var g = document.getElementsByTagName('audio');
for (var i = 0, len = g.length; i < len; i++){

    (function(index){
        // g[i].ended = function(){
        //       alert(index)  ;
        // };
        //g[i].addEventListener("ended", holler(g[i]+1));
        try{
            g[i].addEventListener("ended", g[i+1].play());
        } catch(e){

        }

    })(i);  

}
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • See also [Load multiple audio files one with jquery and have a callback on complete](http://stackoverflow.com/questions/42064108/load-multiple-audio-files-one-with-jquery-and-have-a-callback-on-complete/) – guest271314 Feb 12 '17 at 22:11
  • 1
    @JaromandaX jQuery is not necessary at either pattern at respective Answers. – guest271314 Feb 12 '17 at 22:14
  • Yea, I don't want jQuery. I'll figure it out and post the answer. The IIFE/anon is like my 25th attempt. [We'll Do it LIVE. FkIT We'll Do it LIVE.](https://www.youtube.com/watch?v=Qy-Y3HJNU_s) – Ronnie Royston Feb 12 '17 at 22:22
  • looks like i need to incorporate `.addEventListener('load'`. Anyways, I'll get it working then paste my answer into the duplicate. @guest271314 I appreciate your help but way to much clever code. Dumb it down and make it more consumable, IMHO. – Ronnie Royston Feb 12 '17 at 22:44
  • 1
    remove `()` from `g[i+1].play()` ... problem solved - you can also remove the IIFE (as you aren't using `index` anyway) and you can remove the try/catch if you set `len = g.length - 1` – Jaromanda X Feb 12 '17 at 22:46
  • Figured it out. [Here you go](http://stackoverflow.com/a/42194882/4797603). I'd love to hear if anyone can optimize.... – Ronnie Royston Feb 13 '17 at 00:25
  • @RonRoyston An alternative approach could be to create a single mix track including the each of the audio tracks in sequence, then play the single track [Is it possible to mix multiple audio files on top of each other preferably with javascript](http://stackoverflow.com/questions/40570114/is-it-possible-to-mix-multiple-audio-files-on-top-of-each-other-preferably-with/) – guest271314 Feb 13 '17 at 00:35

0 Answers0