Audio and Video
What Is It?
Audio plays sound. Video plays a recording. Add controls so people can start, pause, and adjust playback.
What the Tags Mean
audio: a sound player.video: a video player.controls: shows playback buttons.source: a media file choice.track: a caption file.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio and Video</title>
</head>
<body>
<audio id="sound" controls></audio>
<script>
// Generate a one-second tone, so no audio file is needed.
const samples = 8000;
const bytes = new ArrayBuffer(44 + samples * 2);
const view = new DataView(bytes);
function text(at, value) {
for (let i = 0; i < value.length; i++) view.setUint8(at + i, value.charCodeAt(i));
}
text(0, "RIFF"); view.setUint32(4, 36 + samples * 2, true);
text(8, "WAVEfmt "); view.setUint32(16, 16, true);
view.setUint16(20, 1, true); view.setUint16(22, 1, true);
view.setUint32(24, 8000, true); view.setUint32(28, 16000, true);
view.setUint16(32, 2, true); view.setUint16(34, 16, true);
text(36, "data"); view.setUint32(40, samples * 2, true);
for (let i = 0; i < samples; i++) {
view.setInt16(44 + i * 2, Math.sin(2 * Math.PI * 440 * i / 8000) * 5000, true);
}
document.getElementById("sound").src = URL.createObjectURL(new Blob([bytes], { type: "audio/wav" }));
</script>
</body>
</html>Browser preview
What you see: Press Play to hear a one-second tone. The script creates the sound inside the page, so no audio file is needed.
Example 2: Another Use
Choose a video from your computer, then press Play. The file stays on your computer; it is not uploaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio and Video</title>
</head>
<body>
<label for="recording">Choose a video from your computer</label>
<input id="recording" type="file" accept="video/*">
<video id="player" controls width="320"></video>
<p id="status">Choose a supported video file, then press Play.</p>
<script>
const player = document.getElementById("player");
let url;
document.getElementById("recording").addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) return;
if (url) URL.revokeObjectURL(url);
url = URL.createObjectURL(file);
player.src = url;
document.getElementById("status").textContent = "Selected: " + file.name;
});
player.addEventListener("error", () => {
document.getElementById("status").textContent = "This browser cannot play that file. Try another video.";
});
</script>
</body>
</html>Browser preview
Simple Tip
The audio script only creates a sample sound. In a real page, use your recording with audio src. Add captions for spoken video and a transcript for audio.
Try It Yourself
Add your own audio file and test Play and Pause.