javascript - Possible to play a sound twice in a row in html 5? -


i'm trying build simon game user must remember sounds being played in right sequence. i've wired audio , fires correctly when element clicked. however, audio not play same sound twice in row unless click twice. in other words, cannot have computer simulate pressing button 2 times in row.

this simplified except js file:

attempt 1 (calling function twice):

... var redbutton    = document.getelementbyid("red"); var audiored     = document.getelementbyid("audio-red");  redbutton.addeventlistener("click", function() {    createnewseq(); }); ...  var createnewseq = function () {   audiored.play();   audiored.play(); }; 

audiored fire 1 time.

attempt 2 (trying force reload calling load function):

var createnewseq = function () {   audiored.play();   audiored.load();   audiored.play(); }; 

same issue - plays single time.

attempt 3 (re-building element): attempt thought of literally re-building , re-loading audio tag on every firing of method seems ridiculous , laughably inefficient.

attempt 4 (create delay settimeout): again, know terrible , inaccurate if problem timing it's possible prevent same thing being called @ same time obscuring if it's been called or not.

attempt 5 (changing source of audio element force reload): thought if change source of element change back, force view second change distinct first.

is audio accessible beginner or need work streams , buffers work?

use media events trigger on ended event. if think it, you're trying play, load, play @ same time. it's saying, "play, load, play!" without waiting finish.

note, don't know browser support media events (the demo doesn't work in ie11 due access restrictions on file source, works in chrome , firefox latest).

demo (plays twice on button click):

<audio id="audiotag1" src="https://upload.wikimedia.org/wikipedia/en/9/9f/sample_of_%22another_day_in_paradise%22.ogg" preload="auto"></audio> <button type='button' id='test'>play sound</button> <span id='played'>0</span>  var audiotag = document.getelementbyid('audiotag1'),     test = document.getelementbyid('test'),     played = document.getelementbyid('played'),     times_played = 0,     max_plays = 2;  test.addeventlistener('click', function() {     audiotag.play();      times_played++;     played.textcontent = 'play #: ' + times_played; });  audiotag.addeventlistener('ended', function(){     console.log('run again', times_played);      if (times_played >= max_plays) {         times_played = 0;         played.textcontent = 'play #: ' + times_played;          return;     }      audiotag.currenttime = 0;     audiotag.play();      times_played++;     played.textcontent = 'play #: ' + times_played; }); 

http://jsfiddle.net/x7xyblus/3/


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -