During this time, developers often asked the same question repeatedly. Why can't I play a local media file 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 systems, cameras, microphones, etc.), unless it is permitted by the user in advance. This restriction is also necessary for browsers. Imagine that if JavaScript can access the local file system without authorization, it will become easy to steal user privacy data, when a user accesses a webpage on the network, the credit card number and password stored on his or her machine are unconsciously displayed, private files such as company secrets may have been uploaded to a remote server by malicious JavaScript programs, which is intolerable to users.
After obtaining the user's permission, we can still play the local file. The following describes a method.
Insert an input node in the page and specify the type as file. To play multiple files, you can add the attribute multiple. Registers the callback function when the file node is updated and calls the URL in the callback function. the createObjectURL function is used to obtain the url of the selected file and set the url to the src value of audio or video.
The code example is as follows:
- <Html>
- <Body>
- <Input type = "file" id = "file" onchange = "onInputFileChange ()">
- <Audio id = "audio_id" 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 passed the test on Chrome 30 and Firefox 24, and there should be some compatibility issues on IE (as far as I know, IE8 and earlier versions certainly cannot work ), because IE does not support HTML5 well, I do not know whether IE10 has implemented related APIs.