vendredi 17 août 2018

Play sound on setInterval

Im trying to display an image, play a random sound and display a random name by a random time. Everything works but the sound. It only plays sometimes.. I have no idea on how to fix it - Maybe another way to play the sound of some sort. Got any suggestions?

<script>

document.getElementById('myimage').style.display = 'none';

var mytime = new Array("12000", "22000");
var randomtime = mytime[Math.floor(Math.random() * mytime.length)];

  window.setInterval(function(){
  /// call your function here

//WORKS
document.getElementById('myimage').style.display = 'block';

var myarray = new Array("Camilla", "Charlotte", "Beata", "Katrine", "Peppe", "Vorre", "Rene", "Schmidt", "Søholm", "Uffe", "Kromann");
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML=random;

var collection=[];// final collection of sounds to play
var loadedIndex=0;// horrible way of forcing a load of audio sounds

function init(audios) {
for(var i=0;i<audios.length;i++) {
var audio = new Audio(audios[i]);
collection.push(audio);
buffer(audio);
}}

function buffer(audio) {
if(audio.readyState==4)return loaded();
setTimeout(function(){buffer(audio)},100);
}

function loaded() {
loadedIndex++;
if(collection.length==loadedIndex)playLooped();
}

function playLooped() {
var audio=Math.floor(Math.random() * (collection.length));
audio=collection[audio];
audio.play();
}

window.setTimeout(function(){
document.getElementById("message").innerHTML="THE-CAMEL-YELLING-DRINKING-GAME";
document.getElementById('myimage').style.display = 'none';
}, 10000);

init([
'sound/camel1.mp3',
'sound/camel2.mp3',
'sound/camel3.mp3'
]);


},randomtime);

</script>




Aucun commentaire:

Enregistrer un commentaire