Playing an Audio File Using JavaScript

Over here, we will using HTML5 and JavaScript to fulfill the need. And the thing to do is to add an audio element to the page which can be seen on a browser. The audio must play when clicked a button.

Using HTML5 Audio Element

HTML stands for Hyper Text Markup language. This is what people see on the browser. Over here by using HTML we are inserting the audio element and see how it’s working on the browser window.

Detailed Procedures:

  1. The first thing to add an audio element into the HTML file
  2. The second thing is to add controls in JavaScript.

Implementation

The below is the implementation

HTML and JavaScript code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Play Audio with JavaScript and HTML</title>
</head>
<body>
    <!-- Step 1: Add the audio element -->
    <audio id="myAudio" src="path/to/your/audiofile.mp3" type="audio/mpeg"></audio>
    
    <!-- Buttons to control the audio playback -->
    <button onclick="playAudio()">Play</button>
    <button onclick="pauseAudio()">Pause</button>
    <button onclick="stopAudio()">Stop</button>

    <!-- Link to the JavaScript file -->
    <script src="script.js"></script>
</body>
</html>
// Get the audio element
let audio = document.getElementById('myAudio');

// Function to play the audio
function playAudio() {
    audio.play();
}

// Function to pause the audio
function pauseAudio() {
    audio.pause();
}

// Function to stop the audio and reset the playback
function stopAudio() {
    audio.pause();
    audio.currentTime = 0;
}

Explanation of the Code

HTML Structure:
1. The audio element with the id of myAudio is defined with a source attribute src pointing to the audio file location. Please enter path file according to your system
2. Three buttons are provided to control the audio: Play, Pause, and Stop. All these buttons are linked to a corresponding JavaScript function.
JavaScript Functions:
1. playAudio(): Which starts to play the audio.
2. pauseAudio(): This function pauses the audio which is playing.
3. stopAudio(): This resets the audio and make it 0.

Running the Example

To see the example in action, follow these steps:

  1. Initialize the HTML File: Save the HTML code as home.html.
  2. Create the JavaScript File: Save the JavaScript code in a file named script.js in the same directory as home.html.
  3. Audio File: Ensure you have an audio file (e.g., audiofile.mp3) and place it in the correct path specified in the src attribute of the <audio> element.
  4. Check on the browser: Open home.html in a web browser to see the audio controls and test the play, pause, and stop functionality.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top