'Play sound when button clicked html
I want to make that when you click on a button it makes a sound, i tryed this:
<script type="text/javascript">
var audio = new Audio('audio_file.mp3');
</script>
<button id="Draw/Chat" onclick="audio.play();" type="button" style="font-weight:bold; background: none rgb(0, 255, 0); border: none; color: rgb(255, 255, 255); box-shadow: none; height: 52px; width: 110px; left: 190px; top: 80px; border-radius: 5px; cursor: pointer; position: absolute;">Draw/Chat</button>
Solution 1:[1]
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
</body>
</html>
Try this code, please
Solution 2:[2]
Don't use a semicolon in the onclick function:
<script type="text/javascript">
var audio = new Audio('audio_file.mp3');
</script>
<button id="Draw/Chat" onclick="audio.play()" type="button" style="font-weight:bold; background: none rgb(0, 255, 0); border: none; color: rgb(255, 255, 255); box-shadow: none; height: 52px; width: 110px; left: 190px; top: 80px; border-radius: 5px; cursor: pointer; position: absolute;">Draw/Chat</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KpStar |
| Solution 2 | MaxCodes |
