Play two files in a row in JavaScript

I can’t get it right. So, I am making a simple script that reports the current time. audiocontainer is an audio element and the mp3play () function was solved earlier. The idea is to do this:

[play hourXX.mp3] β†’ when it ends β†’ [play minutesXX.mp3] β†’ remove the listener, so stop.

  • The problem is this:

Without the removeEventListener () function, the duration of the minutes XX.mp3 is infinite ("It's 12 and 54 minutes ... 54 minutes ... 54 minutes ...), because it continues to run the listener at the end.

Using the removeEventListener () function, the sound does not start at all. Do you know, why?

Or maybe there is an easier way to play 2 mp3 in a row?

function telltime() { var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); audiocontainer.addEventListener('ended', function () { mp3play('./time/minutes/minute'+m.toString()+'.mp3'); audiocontainer.removeEventListener('ended', function(), false); // stop! }, true); mp3play('./time/hours/hour'+h.toString()+'.mp3'); } 
+4
source share
1 answer

Since your problem is a bit "localized" (it does not work due to syntax errors), I have distracted your question to allow me to provide an answer that is useful for others as well.

How to play multiple mp3 files per line

include this in your context:

 var Mp3Queue = function(container, files) { var index = 1; if(!container || !container.tagName || container.tagName !== 'AUDIO')throw 'Invalid container'; if(!files || !files.length)throw 'Invalid files array'; var playNext = function() { if(index < files.length) { container.src = files[index]; index += 1; } else { container.removeEventListener('ended', playNext, false); } }; container.addEventListener('ended', playNext); container.src = files[0]; }; 

use it as follows:

 //whatever is your audio element var container = document.getElementById('container'); //play files in a row new Mp3Queue(container, [ 'http://incompetech.com/music/royalty-free/mp3-royaltyfree/Sweeter%20Vermouth.mp3', 'http://incompetech.com/music/royalty-free/mp3-royaltyfree/Happy%20Boy%20Theme.mp3' ]); 

here is a working example: http://jsfiddle.net/fYjLx/

In your specific case, it will be:

 function telltime() { var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); new Mp3Queue(container, [ './time/hours/hour'+h.toString()+'.mp3', './time/minutes/minute'+m.toString()+'.mp3' ]); } 
+8
source

Source: https://habr.com/ru/post/1484390/


All Articles