During this period, I often see developers repeatedly asking the same question, why can’t I play local media files 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 the file system, camera, microphone, etc.) without prior permission from the user. It is also necessary for browsers to impose this restriction. Just imagine, if JavaScript can access the local file system unscrupulously, it will be easy to steal user private data. When the user accesses a web page on the Internet, he or she will not know what to do. Unknowingly, private files such as credit card numbers, passwords, and company secret files saved on your machine may have been uploaded to a remote server by a malicious JavaScript program, which is intolerable to users.
We can still play local files after getting the user's permission. Here is a method.
Insert an input node into the page and specify 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. In the callback function, call the URL.createObjectURL function to obtain the URL of the just selected file, and then set the URL to the src value of audio or video.
The code example is as follows: