简体   繁体   中英

Play sound when image is loaded

I'm using this code, that plays the sound when the image is clicked (it also changes to another image) and I use it as a play button, but to start music you need to press the ''button''/image, I wish that it could start playing music automatically when the page is loaded. And also so it changes the image to another automatically when the sound starts playing. Do you know how to fix that? Or send me a link if there is already answer with that.

My Code:

 <script type="text/javascript">
  //Create new function that will update the image source on click.
  function updateImage(el, soundfile) {
      //Determine if music is playing or paused then adjust image source 
  accordingly.
      if(soundfile.mp3.paused) {
          el.src = 
"https://static.wixstatic.com/media/e2aefa_33b18f
 bb324d4a569497d1e9758fa65a~mv2.png/v1/fill/w_50,h_50,al_c/e2aefa_33b18
 fbb324d4a569497d1e9758fa65a~mv2.png";
         } else {
          el.src = "https://static.wixstatic.com/media/e2a
 efa_ec0b5b09130f4061a4ad377706732cb8~mv2.png/v1
 /crop/x_0,y_0,w_49,h_45/fill/w_49,h_45,al_c/e2aefa_ec0b5b091
30f4061a4ad377706732cb8~mv2.png";
      }
  };

  function playSound(el,soundfile) {
      if (el.mp3) {
          if(el.mp3.paused) el.mp3.play();
          else el.mp3.pause();
      } else {
          el.mp3 = new Audio(soundfile);
          el.mp3.play();
      }
      //Call new function made whenever the sound is toggled.
      updateImage(document.getElementById("Bottom-1"), el);
  };
</script>
<body>
 <span id="dummy" onclick="playSound(this, 
 'http://listen.shoutcast.com/newfm64aac-');">
 <img src="https://static.wixstatic.com/media/e2aefa_33b18fbb324d4
 a569497d1e9758fa65a~mv2.png/v1/fill/w_50,h_50,al_c/e2aefa_33
 b18fbb324d4a569497d1e9758fa65a~mv2.png.png" name="Bottom-1" width="50" 
 height="45" border="0" id="Bottom-1"/>
 </span>
 </body>

 function myFunction() { //On Click document.getElementById('audio').play(); } function OnLoad() { //On Load Of Image document.getElementById('audio').play(); } 
 <p> cliuck On image to Play Sound </p> <p> You Can Also Use This OnLoad On Body Tag Or Any Where You Want</p> <img src="https://i.stack.imgur.com/k6zs3.png" onclick="myFunction()" onload="OnLoad()" width="42" height="42"> <audio id="audio" controls style="display:none"> <source src="http://butlerccwebdev.net/support/html5-video/media/soundfile.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> 

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