How to play a notification sound on websites?

 


Syntax

var audio = new Audio(URL); audio.play();


Example 1 Using the JavaScript

<html> <body> <h2> Adding the <i> notification sound </i> to webpage using JavaScript </h2> <button onclick = "playSound()"> play notification sound </button> <script> function playSound() { var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/alien_shoot.wav'); audio.play(); } </script> </html>


Example 2 Using the jQuery


<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.js"></script> </head> <body> <h2> Adding the <i> notification sound </i> to webpage using jQuery </h2> <button id = "btn"> play notification sound </button> <script> // play notification sound $("#btn").click(function () { var audio = new Audio('http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg'); audio.play(); }); </script> </html>

Example 3 (Appending audio to the HTML)

<html> <body> <h2> Adding the <i> notification sound </i> to webpage using JavaScript </h2> <div id = "sound"> </div> <button onclick = "playSound()"> play notification sound </button> <script> function playSound() { var mp3 = '<source src="http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg" type="audio/mpeg">'; document.getElementById("sound").innerHTML = '<audio autoplay="autoplay">' + mp3 + "</audio>"; } </script> </html>



แสดงความคิดเห็น (0)
ใหม่กว่า เก่ากว่า