我想在浏览器中从本地磁盘播放视频文件,所以我找到了这段代码。你能告诉我它为什么不起作用吗?在jsfiddle它工作,但当我将其复制到项目中它将无法正常工作。你也可以告诉我什么给出了像function name(x){variables}(window)
这样的函数声明。
我得到的错误是Uncaught TypeError: Cannot read property 'addEventListener' of null
感谢您的帮助:)
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
(function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' +
'<a href="http://caniuse.com/bloburls">supported</a>!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}(window));
</script>
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
</body>
</html>
答案 0 :(得分:1)
问题是,在准备好/加载DOM之前,您的代码正在运行。
有两种解决方法。
1)将整个javascript代码块移到<video controls autoplay></video>
或
2)像这样使用document.addEventListener("DOMContentLoaded", function() { });
:
<script>
document.addEventListener("DOMContentLoaded", function() {
var URL = window.URL || window.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector(("input[type=file]"));
if (!URL) {
displayMessage('Your browser is not ' +
'<a href="http://caniuse.com/bloburls">supported</a>!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
});
</script>