Open In App

How to get Audio from an HTML Video File ?

To extract audio from an HTML video file, we can use the Web Audio API. First, utilize a file input in HTML to allow users to select a video file. Then, employ JavaScript to read the selected video file, decode its audio data using the Web Audio API, and finally, play the extracted audio. This approach enables seamless audio extraction and playback directly within the web browser.

Preview



Approach

Example: Implementation to show how to get audio from an HTML video file.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <title>Audio Extractor</title>
    <link rel="stylesheet" href="styles.css">
</head>
  
<body>
    <input type="file"
           id="videoInput" 
           accept="video/*">
    <script src="script.js"></script>
</body>
  
</html>




/* styles.css*/
body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin: 50px;
}
  
input[type="file"] {
    padding: 10px;
    font-size: 16px;
    cursor: pointer;
    border: 2px solid rgb(20, 20, 233);
    border-radius: 5px;
    background-color: #fff;
    color: rgb(20, 20, 233);
}




// script.js
document.getElementById('videoInput')
    .addEventListener('change', handleFileSelect);
  
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        extractAndPlayAudio(file);
    }
}
  
function extractAndPlayAudio(videoFile) {
    const audioContext = 
        new (window.AudioContext || window.webkitAudioContext)();
    const reader = new FileReader();
  
    reader.onload = function () {
        const arrayBuffer = reader.result;
        audioContext.decodeAudioData(arrayBuffer, function (buffer) {
            playAudio(buffer);
        }, function (error) {
            console.error('Error decoding audio: ', error);
        });
    };
  
    reader.readAsArrayBuffer(videoFile);
}
  
function playAudio(buffer) {
    const audioContext = 
        new (window.AudioContext || window.webkitAudioContext)();
    const source = audioContext.createBufferSource();
    source.buffer = buffer;
    source.connect(audioContext.destination);
    source.start();
}

Output: Here, the audio will played as soon as you choose any video file from your computer.




Article Tags :