加载图像时播放声音

时间:2018-01-21 10:51:13

标签: javascript html

我使用此代码,在单击图像时播放声音(它也会更改为另一个图像)并将其用作播放按钮,但要启动音乐,您需要按下&#39 ;'按钮' /图像,我希望它可以在加载页面时自动开始播放音乐。此外,当声音开始播放时,它会自动将图像更改为另一个。 你知道怎么解决这个问题吗?或者如果已经有答案,请给我一个链接。

我的代码:

 <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>

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
function myFunction() {

//On Click
     document.getElementById('audio').play();
     
}

function OnLoad() {

//On Load Of Image
     document.getElementById('audio').play();
     
}
&#13;
<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>
&#13;
&#13;
&#13;