Comment: After getting the user's permission, we can still play the local file. Insert an input node into the page and specify the type as file, and then set the url to the src value of audio or video.
During this period, developers are often seen repeatedly asking the same question, why can't local media files be played by setting the src attribute? For example video.src=D:/test.mp4.
This is because JavaScript in the browser cannot directly access local resources (such as file system, camera, microphone, etc.), unless the user's permission is obtained in advance. It is also necessary for browsers to implement this restriction. Just imagine that if JavaScript can access the local file system unscrupulously, stealing user privacy data will become easy. When a user visits a web page on the network, the credit card number, password, company secret files and other privacy files saved on his machine may have been uploaded to a distant server by malicious JavaScript programs, which is intolerable to users.
After obtaining the user's permission, we can still play local files. Here is a method.
Insert an input node into the page and specify the type as file. If you need to play multiple files, you can add the attribute multiple. Register the callback function when the 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.
The code example is as follows:
<html>
<body>
<input type="file" onchange="onInputFileChange()">
<audio controls autoplay loop>Your browser can't support HTML5 Audio</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>
This code was tested and passed on Chrome 30 and Firefox 24. There should be some compatibility issues on IE (as far as I know, IE8 and previous versions definitely cannot work), because IE does not support HTML5 well, and I don’t know if IE10 implements related APIs.