使用HTML和JavaScript播放本地的媒体(视频音频)文件的方法
To play local media (video/audio) files using HTML and JavaScript, you can follow these steps:
1. HTML Structure:
Create an HTML document with the following structure:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Local Media Player</title>
</head>
<body>
<video id="myVideo" width="640" height="360" controls>
<source src="path/to/your/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<audio id="myAudio" controls>
<source src="path/to/your/audio.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
<script src="script.js"></script>
</body>
</html>
"path/to/your/video.mp4"
and "path/to/your/audio.mp3"
with the actual paths to your local media files.controls
attribute adds default playback controls to the media elements.2. JavaScript for Additional Control (Optional):
In the script.js
file, you can add JavaScript code to gain more control over the media playback:
const videoElement = document.getElementById('myVideo');
const audioElement = document.getElementById('myAudio');
// Play the video when the page loads
videoElement.play();
// Pause the video when a button is clicked
const pauseButton = document.getElementById('pauseButton');
pauseButton.addEventListener('click', () => {
videoElement.pause();
});
// Mute the audio when a button is clicked
const muteButton = document.getElementById('muteButton');
muteButton.addEventListener('click', () => {
audioElement.muted = !audioElement.muted;
});
// Seek to a specific time in the video
const seekSlider = document.getElementById('seekSlider');
seekSlider.addEventListener('input', () => {
const currentTime = seekSlider.value * videoElement.duration;
videoElement.currentTime = currentTime;
});
Key Points:
src
attributes.