Use HTML and JavaScript to open a window to play local media (video and audio) files

Use HTML and JavaScript to select and play local media (video and audio) files in the open window

First of all, if you need JavaScript to be safe, you can't directly use the open window to access local resource files. What should I do? One method is described below. Insert an input node in the page and specify the type as file. If you need to play multiple files, you can add the attribute multiple. The callback function when the registered file node is updated, call the URL.createObjectURL function in the callback function to get the url of the file just selected, and then set the url to the src value of audio or video.

 

1. An example of using HTML and JavaScript to open a window to play a local video file , the source code is as follows:

​<!DOCTYPE html>
<html >
<head>
       <meta charset="utf-8"> 
       <title>播放本地的视频文件</title>
</head>
<body>
<h3><center>播放本地的视频播放测试<center></h3>
<hr color="#666666">
<input type="file" id="file" onchange="onInputFileChange()">
<br/>
<video id="video_id"  width="520" height="360" controls autoplay loop>你的浏览器不能支持HTML5视频</video>
<script>
function onInputFileChange() {
      var file = document.getElementById('file').files[0];
      var url = URL.createObjectURL(file);
      console.log(url);
      document.getElementById("video_id").src = url;
}
</script>
</body>
</html>

Save it as the file name DemoF.html (here, I put the webpage file in the directory D:\webpage practice, you can decide according to your actual situation), open it with a browser and display it as follows:

 

 

2. An example of using HTML and JavaScript to open a window to play a local audio file , the source code is as follows:

<!DOCTYPE html>
<html >
<head>
       <meta charset="utf-8"> 
       <title>播放本地的音频文件</title>
</head>
<body>
<h3><center>本地的音频播放测试<center></h3>
<hr color="#666666">
<input type="file" id="file" onchange="onInputFileChange()">
<br/>
<audio id="audio_id"  controls autoplay loop>你的浏览器不能支持HTML5音频 </audio>
<script>
function onInputFileChange() {
      var file = document.getElementById('file').files[0];
      var url = URL.createObjectURL(file);
      console.log(url);
      document.getElementById("audio_id").src = url;
}
</script>
</body>
</html>

Save it as the file name DemoG.html (here, I put the webpage file in the directory D:\webpage practice, you can decide according to your actual situation), open it with a browser and display it as follows:

Click the "Select File" button to pop up the "Open" file dialog box to load the audio file for playback.

 

 

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/113835795