Home > Web Front-end > H5 Tutorial > HTML5 Video/Audio local file playback example introduction_html5 tutorial skills

HTML5 Video/Audio local file playback example introduction_html5 tutorial skills

WBOY
Release: 2016-05-16 15:48:34
Original
1794 people have browsed it

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:

Copy the code
The code is as follows:

< html>



<script> <br>function onInputFileChange() { <br> var file = document.getElementById('file').files[0]; <br> var url = URL.createObjectURL(file); <br> console.log(url); <br> document.getElementById("audio_id").src = url; <br>} <br></script>



This code has been tested on Chrome 30 and Firefox 24. There should be certain compatibility issues on IE (as far as I know IE8 and previous versions will definitely not work), because IE does not support HTML5 well, and I don’t know if IE10 has implemented the relevant API.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template