How to Use Javascript to Play an MP3 File

Written by michael carroll
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Use Javascript to Play an MP3 File
Use a JavaScript function to let website visitors play an MP3. (Jupiterimages/Comstock/Getty Images)

A number of ways are possible to embed and play MP3 audio files on your Web pages. The deprecated "embed" tag in HTML, various Flash players, and Java-based players are all examples. The HTML5 standard, with its emphasis on scripting and its lack of reliance on third-party software, offers the most compatible way to embed and play MP3s on Web pages going forward. Embed the MP3 file with the HTML5 "audio" object, and then use a JavaScript function to start it playing

Skill level:


  1. 1

    Add the following code to the body of your HTML document:

    <audio src="audio.mp3" id="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. 2

    Add the following JavaScript code between the "head" tags of your HTML document:

    <script type="text/javascript">

    function playMP3(){




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

  3. 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" on Click="playMP3();" />

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

  4. 4

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

    function playpauseMP3(){







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

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.