Play sound file when image is clicked

前端 未结 3 571
-上瘾入骨i
-上瘾入骨i 2020-12-09 21:51

I am not a native HTML programmer, so please don\'t jump all over me about this simple question.

I have an image that, I am displaying using the followi

相关标签:
3条回答
  • 2020-12-09 22:23

    First you have to use jQuery. You may create some <div> in your page having some id, for example;

    <div id="wrap">&nbsp;</div>.

    Then, in your JavaScript, when you want to play the file, just add

    $('#wrap').append('<embed id="embed_player" src="audio.wav" autostart="true" hidden="true"></embed>');
    

    the whole code looks something like;

    <script type="text/javascript" src="jquery-1.7.1.js"></script>
    <script type="text/javascript">
    $(document).ready( function() {
    $('#track1').click(function(){
       $('#wrap').append('<embed id="embed_player" src="audio.wav" autostart="true" hidden="true"></embed>');
    });
    });
    </script>
    <img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" />
    <div id="wrap">&nbsp;</div>
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-09 22:29
    <html>    
        <body>
            <div id="container">
                 <img name="track1" src="images/track1.png" width="180" height="180" border="0" id="track1" alt="" class="play" />
            </div>
        </body>
    </html>
    


    <script>
            $(document).ready(function() {
                var audioElement = document.createElement('audio');
                audioElement.setAttribute('src', 'audio.mp3');
                audioElement.setAttribute('autoplay', 'autoplay');
                //audioElement.load()
    
                $.get();
    
                audioElement.addEventListener("load", function() {
                    audioElement.play();
                }, true);
    
                $('.play').click(function() {
                    audioElement.play();
                });
    
                $('.pause').click(function() {
                    audioElement.pause();
                });
            });
        </script>
    
    0 讨论(0)
  • 2020-12-09 22:37

    This answer by @klaustopher helped me. He wrote:

    HTML5 has the new -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></p>
    
    0 讨论(0)
提交回复
热议问题