简体   繁体   English

使用HTML-CSS-JS在触摸事件上播放MP3

[英]Play MP3 on touch event with HTML-CSS-JS

could someone help me in finding a way to play an mp3 audio file by touching an image on a touch screen with HTML-CSS-JavaScript? 有人可以帮助我找到一种通过使用HTML-CSS-JavaScript在触摸屏上触摸图像来播放mp3音频文件的方法吗?

Thank you! 谢谢!

<!DOCTYPE HTML>
  <html>
  <head>
  <title>audio with image</title>
  </head>
  <body>

    <script>
  function play(){
       var audio = document.getElementById("audio");
       audio.play();
                 }
   </script>

<img src="http://www.partyplan123.com/wp-content/uploads/2015/02/click-here.jpg" onclick="play()">
<audio id="audio" src="http://kolber.github.io/audiojs/demos/mp3/juicy.mp3" ></audio>
 </body>
 </html>

To play an audio file in HTML, use the <audio></audio> tag. 要以HTML格式播放音频文件,请使用<audio></audio>标记。
This tag also comes with <audio controls> attribute, to add controls like play pause and all. 该标签还带有<audio controls>属性,用于添加播放暂停等所有控件。
For a full DOM documentation on this tag go to the W3 audio tag docs 有关此标记的完整DOM文档,请转到W3音频标记docs
As for the JS side, use the onclick() event for triggering the audio file on touch. 至于JS端,请使用onclick()事件触发触摸时的音频文件。

Create an audio element in your html and hide it using visibility: hidden . 在您的html中创建音频元素,并使用“ visibility: hidden隐藏它。

When the user clicks on the image, handle the click event with Javascript and trigger play on the audio element manually from the handler. 用户单击图像时,使用Javascript处理click事件,并从处理程序中手动触发音频元素上的播放。

You can refer here for more documentation on audio html api's. 您可以在此处参考有关audio html API的更多文档

Here's the best way. 这是最好的方法。 This is not inline Javascript so complies to Content Security Policies (CSP's) so if you port to android .apk or to a chromium app, you won't have issues. 这不是内联Javascript,因此符合内容安全策略(CSP),因此,如果您移植到android .apk或Chrome应用,则不会有任何问题。 This is not my code obviously, its from Steven Park on teamtreehouse: The first way using Jquery: 这显然不是我的代码,它来自teamtreehouse上的Steven Park:使用Jquery的第一种方法:

const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
    $('#dice-button').click(e => rollSound.play());

Create aa div with the #div-button name, and also another example a version that is not JQuery: 使用#div-button名称创建一个div,以及另一个示例(不是JQuery):

const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
    document.getElementById('dice-button').addEventListener("click", e => 
    rollSound.play());

You can find it here: https://teamtreehouse.com/community/how-do-i-add-a-sound-when-a-button-is-clicked-jquery 您可以在这里找到它: https : //teamtreehouse.com/community/how-do-i-add-a-sound-when-a-button-is-clicked-jquery

However I have cut and paste it because it took me hours to find that solution after searching for something that fills my needs. 但是,我已将其剪切并粘贴,因为在寻找满足我需求的东西之后花了我几个小时才能找到该解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM