Search code examples
javascriptaudiocodepen

Javascript HTML play sound only once, but more strange thing happened


I tried this simple snippet in codepen. and function once1 can play as many times as you want while once2 can play sound only once. Anyone know what's the difference?

var  simple = new 
Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new 
Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');

birdSound.loop = false;
simple.loop = false;
function once1(){
  birdSound.play(); 
};
function once2(){
  simple.play(); 
};

Solution

  • Here you go, I saw the other answer still wasn't working on jsfiddle or codepen so try this!

    var  simple = new 
    Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
    var birdSound = new 
    Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
    
    birdSound.loop = false;
    simple.loop = false;
    function once1(){
        birdSound.load();
      birdSound.play(); 
    };
    function once2(){
        simple.load();
      simple.play(); 
    };
    

    Just use .load :D