-1

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>
Gacha YTB
  • 17
  • 1
  • 4
  • Please, before posting a question try to check whether it has been asked (and answered) before, using the search function: https://stackoverflow.com/search?q=%5Bjavascript%5D+play+sound+on+button+click – secan Jan 26 '22 at 08:37
  • ... also consider that the audio file might require some time to be loaded therefore it is advisable to check whether it is ready to play before tying to execute it. – secan Jan 26 '22 at 08:45
  • ... finally, you might want to check whether the path to your audio file is correct. In your example 'audio_file.mp3' is supposed to be in the same folder where your HTML page is; is that the case? – secan Jan 26 '22 at 08:55
  • 1
    Does this answer your question? [Javascript Audio Play on click](https://stackoverflow.com/questions/18826147/javascript-audio-play-on-click) – Pavel Schiller Jan 26 '22 at 10:43

2 Answers2

-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

KpStar
  • 122
  • 7
  • this didn't work :/ – Gacha YTB Jan 26 '22 at 08:39
  • https://stackoverflow.com/questions/18826147/javascript-audio-play-on-click I checked and it worked fine, please check again. – KpStar Jan 26 '22 at 08:40
  • 2
    @KpStar what's the point of copying and pasting an already existing answer, without adding anything new/different to it, rather than simply linking it in a comment? – secan Jan 26 '22 at 08:48
-1

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>
MaxCodes
  • 82
  • 10