【问题标题】:Play sound on setInterval在 setInterval 上播放声音
【发布时间】:2018-08-17 09:50:19
【问题描述】:

我正在尝试显示图像,播放随机声音并在随机时间显示随机名称。一切正常,但声音。它有时只播放..我不知道如何修复它 - 也许是另一种播放某种声音的方式。有什么建议吗?

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);
 <img id="myimage" src="dist/images/giphy.gif" width="420" height="236" />
 <h1 id="message">THE-CAMEL-YELLING-DRINKING-GAME</h1>

【问题讨论】:

  • 检查浏览器控制台是否有未处理的承诺拒绝。另外,写代码的时候可以考虑使用缩进,不然会比较难读。
  • @CertainPerformance HTML 添加并且控制台中没有错误
  • 我不知道“骆驼大喊大叫喝酒游戏”是什么,但我很兴奋。

标签: javascript audio random mp3 setinterval


【解决方案1】:

在您的允许下,我整理了一些代码。(只是一点点)我尝试确保所有音频文件都准备好播放,然后开始“循环”。每个 audio.oncanplay 的回调正在增加集合中加载的音频文件的总数。当这个 nr 等于集合中音轨的总数时,我们称为循环。

var nrReadyToPlay = 0;
var collection = [];
var soundtracks = [
  'sound/camel1.mp3',
  'sound/camel2.mp3',
  'sound/camel3.mp3'
];

function audioReady() {
  nrReadyToPlay++;
  // When nr of ready callbacks calls will be equal to the nr of soundtracks then start loop.
  if (nrReadyToPlay !== soundtracks.length) return;
  startLoop()
}

function init(audios) {
  for (var i = 0; i < audios.length; i++) {
    var audio = new Audio(audios[i]);
    audio.oncanplay = audioReady;
    audio.muted = true;
    collection.push(audio);
  }
}
// returns a random name
function setRandomMessage() {
  var myarray = ["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;
}
// plays a random audio file
function playRandomAudio() {
  var audio = collection[Math.floor(Math.random() * (collection.length))];
  audio.muted = false;
  if (audio.readyState !== 4) console.log('ERROR')
  audio.play();
}

function displayImage() {
  document.getElementById('myimage').style.display = 'block';
}

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

  var mytime = [10000, 12000];
  var randomtime = mytime[Math.floor(Math.random() * mytime.length)];

  window.setInterval(function() {
    displayImage();
    setRandomMessage()
    playRandomAudio();
      <html>
        <head>
          <title>My title</title>
        </head>
        <body>

          <image id="myimage" src="pen.jpg"></image>
          <h1 id="message">THE-CAMEL-YELLING-DRINKING-GAME</h1>


          <script>
            var nrReadyToPlay = 0;
            var collection = [];
            var soundtracks = [
              'sound/camel1.mp3',
              'sound/camel2.mp3',
              'sound/camel3.mp3'
            ];

            function audioReady() {
              nrReadyToPlay++;
              // When nr of ready callbacks calls will be equal to the nr of soundtracks then start loop.
              if (nrReadyToPlay !== soundtracks.length) return;
              startLoop()
            }

            function init(audios) {
              for(var i=0;i<audios.length;i++) {
                var audio = new Audio(audios[i]);
                audio.oncanplay = audioReady;
                audio.muted = true;
                collection.push(audio);
              }
            }
            // returns a random name
            function setRandomMessage() {
              var myarray = ["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;
            }
            // plays a random audio file
            function playRandomAudio() {
              var audio = collection[Math.floor(Math.random() * (collection.length))];
              audio.muted = false;
              if (audio.readyState !== 4) console.log('ERROR')
              audio.play();
            }

            function displayImage() {
              document.getElementById('myimage').style.display = 'block';
            }

            function startLoop() {
              document.getElementById('myimage').style.display = 'none';
            
              var mytime = [3000, 5000];
              var randomtime = mytime[Math.floor(Math.random() * mytime.length)];
            
              window.setInterval(function() {
                displayImage();
                setRandomMessage()
                playRandomAudio(); 
                window.setTimeout(function(){
                    document.getElementById("message").innerHTML="THE-CAMEL-YELLING-DRINKING-GAME";
                    document.getElementById('myimage').style.display = 'none';
                }, 10000);     
              }, randomtime);
            }


            init(soundtracks);

            </script>

        </body>
      </html>

  }, randomtime);
}

init(soundtracks);
 <img id="myimage" src="dist/images/giphy.gif" width="420" height="236" />
<h1 id="message">THE-CAMEL-YELLING-DRINKING-GAME</h1>

【讨论】:

  • 仍然不播放声音,只是有时:s 在原始代码中,图像在 10 秒内显示,然后在再次循环之前消失。
  • 首先我已经在本地运行它并且可以保证它可以工作,其次你必须与页面交互,(例如:点击,移动鼠标)否则浏览器将不会播放任何媒体。顺便说一句,我添加了“在再次循环之前消失了”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多