Immediate play sound on button click in HTML page

后端 未结 5 1120
旧巷少年郎
旧巷少年郎 2021-02-02 17:42

In my HTML page I have 9 images for dialing numbers and one text box that shows the pressed numbers. I want each of those images to immediately play beep sound when users click

相关标签:
5条回答
  • 2021-02-02 18:14

    Example based on accepted answer (Tested in Chrome 70), but I didn't need to re-cue:

    <button onclick="snd.play()"> Click Me </button>
    
    <script>
        var snd = new Audio("/Content/mysound.wav"); 
    </script>
    
    0 讨论(0)
  • 2021-02-02 18:15

    This answer https://stackoverflow.com/a/7620930/1459653 by @klaustopher (https://stackoverflow.com/users/767272/klaustopher) helped me. He wrote:

    HTML5 has the new <audio>-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface:

    <audio id="sound1" src="yoursound.mp3" preload="auto"></audio> <button onclick="document.getElementById('sound1').play();">Play it</button>

    Here's how I implemented his advice so that clicking on the Font Awesome icon "fa-volume-up" (located on the Web page after "mule.") results in "donkey2.mp3" sound playing (note: mp3 doesn't play in all browsers).

    <p>In short, you're treated like a whole person, instead of a rented mule. <audio id="sound1" src="assets/donkey2.mp3" preload="auto"></audio><a class="icon fa-volume-up" onclick="document.getElementById('sound1').play();"></a>
    
    0 讨论(0)
  • 2021-02-02 18:15

    You can use embed element for play sounds, but you've to check the formats supported by the different browsers.

    Embed element on MDN

    <a onclick="playSound('1.mp3')">
       <img src="1.gif">
    </a>
    <div id="sound"></div>
    
    <script>
       var playSound = function (soundFile) {
          $("#sound").html("<embed src=\"" + soundFile + "\" hidden=\"true\" autostart=\"true\" />");
       }
    </script>
    
    0 讨论(0)
  • 2021-02-02 18:27

    This code lets you put in a picture button; when click you get a sound. It works with Google Chrome and Microsoft Edge but I can't get it to work in Internet Explorer. I'm using html 5 codes; please copy and paste and add you own samples.

    </head>
    <body>
    <script>
    var audio = new Audio("/Sample.wav ");
    audio.oncanplaythrough = function ( ) { }
    audio.onended = function ( ) { }
    </script> <input type="image" src="file://C:/Sample.jpg" onclick="audio.play ( )">
    </body>
    </html>
    

    more on codes look at http://html5doctor.com/html5-audio-the-state-of-play/

    0 讨论(0)
  • 2021-02-02 18:32

    If you only need to support recent browsers, then HTML 5 offers you the Audio object

    to load/buffer your sound:

    var snd = new Audio("file.wav");
    

    to play the sound:

    snd.play();
    

    to re-cue it to the beginning (so that you can play it again):

    snd.currentTime=0;
    
    0 讨论(0)
提交回复
热议问题