简体   繁体   中英

Javascript and HTML5 loop issue

I'm trying to create a simple loop recording program in HTML5. I have some of the basics done but the problem I'm having now is when I try to play the audio recursively it keeps firing the method before the audio is finished or way after.

I tried to set a setTimeout but thats only confusing me as what I thought would be a correct interval just confused me more. Could someone please look over this?

You can also find an active site http://rossb.byethost11.com/

  /* * finds duration of sound file in milliseconds */ function getMasterDuration() { var sound = document.getElementById("session-1"); var returnValue = sound.duration * 1000; return returnValue; } /* * called from the button */ function playAllService() { //set up recursive loop to play sounds window.setInterval(recursivePlay, getMasterDuration); } function recursivePlay() { //play all sounds playAll(); //set timeout until sound is done (?) setTimeout(recursivePlay, getMasterDuration); } /* * Finds all the recording sessions and plays them. */ function playAll() { for (var i = 1; i <= numberOfSessions; i++) { play(i); } } 

And yes, I know it needs cleanup.

Thanks for the help!

Edit for Clarification: I want it to loop without any breaks. like a loop petal or drum machine.

When you access a function without parentheses, you're referring to the function itself. So a call to recursivePlay returns this:

function recursivePlay() {
  //play all sounds
  playAll();
  //set timeout until sound is done (?)
  setTimeout(recursivePlay, getMasterDuration);
}

This is correct for the first parameter to setTimeout , because you want the function to run after an interval.

The second parameter to setTimeout is expected to be a number (in milliseconds). However, you're returning the function getMasterDuration instead of the result of the function.

To fix that, simply add parentheses to getMasterDuration :

setTimeout(recursivePlay, getMasterDuration());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM