简体   繁体   中英

How do play an audio file on a button click using HTML and JavaScript?

This code only returns a volume icon and a link property, doesn't play audio file:

 function playSound() { var sound = document.getElementById("audio"); sound.play(); }
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="name"> My name is <div> <a><i class="fa fa-volume-up" style="font-size:24px" onclick="playSound()"></i></a> </div> Basiyath Zubair <audio id="audio" src="./audio/name.mp3"></audio> </div>

If you assign the correct URL to the src attribute ofaudio , it will work, eg

 function playSound() { var sound = document.getElementById("audio"); sound.play(); }
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="name"> My name is <div> <a><i class="fa fa-volume-up" style="font-size:24px" onclick="playSound()"></i></a> </div> Basiyath Zubair <audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3"> Your browser does not support the <code>audio</code> element. </audio> </div>

Try this, it may work for you

<!DOCTYPE html>
<html>
<body>
<audio id="myAudio">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>
<p>Click the buttons to play or pause the audio.</p>
<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>
<script>
    var x = document.getElementById("myAudio"); 

    function playAudio() { 
      x.play(); 
    } 

    function pauseAudio() { 
     x.pause(); 
    }
</script> 
</body>
</html>

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