我想要选择一个文件,然后单击按钮后,想要将该文件加载到视频元素中,该元素应该立即播放。
尝试通过 type="text"
输入文件是可行的,但这需要我输入文件的链接。我想要的是能够选择文件,就像通过资源管理器一样。
type="file"
允许我通过资源管理器选择文件,但之后我无法将文件附加到 video.src
中,因为 value
属性返回fakepath
而不是真实路径。还有其他方法吗?
<html>
<head>
<title>Using File For Streaming</title>
</head>
<body>
<input type="file" id="videoUrl"/>
<button onClick="play()">Play Video</button>
<video id="videoPlayer" height="400" width="400" autoplay controls muted></video>
<script>
function play() {
var videoUrl = document.getElementById('videoUrl').value;
alert(videoUrl);
var videoPlayer = document.getElementById('videoPlayer');
videoPlayer.src = videoUrl;
videoPlayer.load();
videoPlayer.play();
}
</script>
</body>
</html>
最佳答案
使用 URL.createObjectURL
方法,用您上传的input.files[0]
喂养你的<source>
的src
,然后调用.load()
你的方法<video>
.
inp.onchange = function(){
source.src = URL.createObjectURL(inp.files[0]);
vid.load();
// even if it's just a pointer to the real file here
vid.onended = function(){
URL.revokeObjectURL(vid.currentSrc);
};
}
<video id="vid" controls>
<source id="source"/>
</video>
<input id="inp" type="file" accept="video/*">
关于javascript - 通过输入类型 ="file"选择文件并将源文件附加到视频元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42082211/