我一直在尝试下载一个视频(最终将来自我自己的资源),当视频正在下载时,我想显示加载消息。
完全下载后,我想隐藏加载图标并准备播放视频。
我无法获取视频文件并将其设置为HTML中的视频属性。这是我正在使用的代码...
JS:
var root = 'https://crossorigin.me/http://techslides.com/demos/sample-videos/small.mp4';
function loadVideo() {
$('.loading').show();
$.ajax({
url: root,
method: 'GET'
}).then(function(data) {
$('.loading').hide();
console.log("done");
$('video').attr('src', data);
$("video")[0].load();
//console.log(data);
});
}
HTML:
<div class="loading animated bounce infinite">
Loading
</div>
<video width="320" height="240" controls>
</video>
答案 0 :(得分:0)
您不需要ajax请求。您只需设置视频元素的来源,然后收听loadeddata
即可。您可以查看4种不同的readyStates。 HAVE_ENOUGH_DATA
(readyState 4)代表:
有足够的数据 - 且下载速度足够高 - 媒体可以不间断地播放到最后。
此实现可能如下所示:
function loadVideo(videoURL, $player) {
$player = $videoObj || $('video');
$('.loading').show();
$player.attr('src', videoURL);
var player = $player[0];
player.addEventListener('loadeddata', function() {
if(player.readyState == 4) {
// or whatever you want to do
// in case the video has enough data
$('.loading').hide();
}
});
}
如果您确实需要“完整”状态(100%),您可以使用progress
事件来确定缓冲视频的数量,以防缓冲区为100%,视频应该完全加载。
function loadVideoCompleted(videoURL, $player) {
$player = $videoObj || $('video');
$('.loading').show();
$player.attr('src', videoURL);
var player = $player[0];
player.addEventListener('loadeddata', function() {
var percentageBuffered = 0;
if (player.buffered.length > 0
&& player.buffered.end && player.duration) {
percentageBuffered = player.buffered.end(0) / player.duration;
} else if (player.bytesTotal != undefined &&
player.bytesTotal > 0 && player.bufferedBytes != undefined) {
percentageBuffered = player.bufferedBytes / player.bytesTotal;
}
if (percentageBuffered == 1) {
// or whatever you want to do in case
// 100% of the video has been buffered
$('.loading').hide();
}
});
}