iFocus.Life News News - Breaking News & Top Stories - Latest World, US & Local News,Get the latest news, exclusives, sport, celebrities, showbiz, politics, business and lifestyle from The iFocus.Life,

How to Use Javascript to Play an MP3 File

104 30
    • 1). Add the following code to the body of your HTML document:

      <audio src="audio.mp3" preload="auto"></audio>

      This code embeds and loads the MP3 file, but does not play it. The value of the "src" tag contains the path to and filename of the MP3 file.

    • 2). Add the following JavaScript code between the "head" tags of your HTML document:

      <script type="text/javascript">

      function playMP3(){

      document.getElementById("mp3").play();

      }

      </script>

      This function, when called, accesses the "audio" element by its id ("mp3"), and uses the method play() to play it.

    • 3). Add a button to the Web page to call the "playMP3" function when the user clicks it. Add the following code to the body of the HTML document:

      <input type="button" value="Click to play MP3" onClick="playMP3();" />

      Change the "value" attribute to give the button a different title.

    • 4). Use the following function instead of "playMP3" to let the user pause the file after starting it:

      function playpauseMP3(){

      if(document.getElementById("mp3").paused){

      document.getElementById("mp3").play();

      }else{

      document.getElementById("mp3").pause();

      }

      }

      Change the "onClick" attribute of the "input" tag in Step 3 to match this function's name.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time
You might also like on "Business & Finance"

Leave A Reply

Your email address will not be published.