我有一个简单的应用,其中有三个不同的视频,我希望每个视频都在特定时间播放。例如:
第一个要播放的视频。
5:00 AM
和10:00 AM
之间。
第二个视频要播放。
10:00 AM
和22:00 PM
之间。
要播放的第三段视频。
22:00 PM
和5:00 AM
之间。
因此,假设用户是否在9:00 AM
左右访问了我的应用。它应该会自动播放第一个视频。如果用户访问11: 00 AM
附近,则会播放第二个视频,依此类推。
我希望函数仅在一天中的特定时间使用javascript和postMessage函数以设置的间隔运行函数,
这是我的解决方案: app.js
var welcomeMovie1 = "http://mirrors.standaloneinstaller.com/video-sample/jellyfish-25-mbps-hd-hevc.mp4";
var welcomeMovie2 = "http://mirrors.standaloneinstaller.com/video-sample/TRA3106.mp4"
var welcomeMovie3 = "http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.mp4";
var messageTime;
//function to play a video1 to iframe using post messages
function welcomeMessage1() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie1)'
}),
'*'
)
}
//function to play a video2 to iframe using post messages
function welcomeMessage2() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie2)'
}),
'*'
)
}
//function to play a video3 to iframe using post messages
function welcomeMessage3() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie2)'
}),
'*'
)
}
//function to play a video1 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
if (messageTime >= 5 && messageTime < 10) {
welcomeMessage1();
console.log(welcomeMessage2());
}
}, 1000 * 60);
//function to play a video2 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
console.log(date.toLocaleString('en-GB'));
if (messageTime >= 10 && messageTime < 22) {
welcomeMessage2();
console.log(welcomeMessage2());
}
}, 1000 * 60);
//function to play a video3 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
if (messageTime >= 22 && messageTime < 5) {
welcomeMessage3();
}
}, 1000 * 60);
// promise function to create custom video controls and play functions
function playVideo(src) {
$("#playervideo").attr("src", src);
$("#playervideo")[0].muted = false;
if (autoplay == true) {
var playPromise = $("#playervideo")[0].play();
if (playPromise !== undefined) {
playPromise.then(function() {}).catch(function() {
if (autoplay == true) {
$("#video-unmute-button").addClass("show");
$("#playervideo")[0].muted = true;
var playPromise2 = $("#playervideo")[0].play();
playPromise2.then(function() {
}).catch(function() {
$("#video-start-button").addClass("show");
$("#video-start-button").on("click", function() {
$("#playervideo")[0].muted = false;
$("#playervideo")[0].play();
$("#video-start-button").removeClass("show");
});
});
console.log("pause force");
} else {
}
});
} else {}
} else {
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Frame</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<iframe id="videoframe" src="videoframe.html"></iframe>
<br/>
<!-- <input id="name" type="text"/> -->
</body>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
</html>
以下是完整演示的缩影:demo
不幸的是,它不起作用,
我需要更改我的代码以获得我想要的东西吗?
答案 0 :(得分:1)
无需使用setInterval
;您只需要使用if
语句或switch case
。
我删除了setInterval
代码,并做了一个if语句。在最后一种情况下,您需要将双与号(&&
/ AND更改为||
(OR)-(>22 OR <5)
-,否则就没有意义。我通过调整系统时钟测试了以下内容,它似乎可以正常工作。
这里是fiddle
节日快乐!
var welcomeMovie1 = "http://mirrors.standaloneinstaller.com/video-sample/jellyfish-25-mbps-hd-hevc.mp4";
var welcomeMovie2 = "http://mirrors.standaloneinstaller.com/video-sample/TRA3106.mp4"
var welcomeMovie3 = "http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.mp4";
var messageTime = new Date().getHours();
var welcomeMsg = "";
var vid = " ";
//console.log(messageTime);
if (messageTime >= 5 && messageTime <= 10) {
welcomeMsg = "early bird";
vid = welcomeMovie1;
//console.log(welcomeMessage2);
}
else
if (messageTime >= 10 && messageTime < 22) {
welcomeMsg = "middle of day";
vid = welcomeMovie2;
//console.log(welcomeMessage2());
}
else
if (messageTime >= 22 || messageTime < 5) {
welcomeMsg = "night owl";
vid = welcomeMovie3;
}
////}, 1000 * 60);
playVideo(vid);
console.log("Hello! Your welcome message is " + welcomeMsg + " " + vid)
// promise functionb to create custom video controls and play functions
function playVideo(src) {
console.log("Hello! Your welcome message is " + welcomeMsg + " " + vid)
$("#playervideo").attr("src", src);
$("#playervideo")[0].muted = false;
if (autoplay == true) {
var playPromise = $("#playervideo")[0].play();
if (playPromise !== undefined) {
playPromise.then(function() {}).catch(function() {
if (autoplay == true) {
$("#video-unmute-button").addClass("show");
$("#playervideo")[0].muted = true;
var playPromise2 = $("#playervideo")[0].play();
playPromise2.then(function() {
}).catch(function() {
$("#video-start-button").addClass("show");
$("#video-start-button").on("click", function() {
$("#playervideo")[0].muted = false;
$("#playervideo")[0].play();
$("#video-start-button").removeClass("show");
});
});
console.log("pause force");
} else {
}
});
} else {}
} else {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe id="playervideo" controls src=" ">
</iframe>
答案 1 :(得分:1)
<iframe>
和<video>
自动播放已不再是以前的样子。要获取<video>
标签以进行自动播放也涉及many restrictions and various criteria。这是需要的:
<video>
标记需要[muted]
和[autoplay]
属性
<video ... muted autoplay></video>
<iframe>
标签需要[allow="autoplay"]
属性。全屏是可选的
<iframe ... allowfullscreen allow="autoplay; fullscreen"></iframe>
在loadVideo()
下面的演示中,该函数根据当前时间将MP4文件加载到<video>
标签的[src]
中。从<iframe>
自动加载媒体非常棘手,因为它们是要加载的DOM内容的最后内容之一。最好在IIFE (Immediately-invoked Function Expression)的子页面(videoframe.html
)中运行函数。
(function() {
loadVideo();
})();
要调用play()
方法,您需要使用Promise API。这是engineers want to overcomplicate it正常工作的另一个实例。
async function promisePlay() {
try {
await document.querySelector('video').play();
} catch (err) {
...
}
}
对于使用postMessage API via <iframe>
的跨域通信,开发人员必须同时拥有两个域的所有权。所有权并不一定意味着完全的管理特权,只是足以使两个页面都可以被实际编辑。 YouTube和Vimeo等一些API也可以满足您的需求。
基本上,父页面(index.html
)将发送一条消息:
window.frames[0].postMessage(data, origin);
window.frames[0]
将获得第一个<iframe>
并访问其窗口内容,等效于:document.querySelector('iframe').contentWindow;
。 data
只是一个字符串。 origin
通常是父页面(index.html
)https://www.example.com
的{{3}}。子页面(videoframe.html
)通过监听location.protocol
and location.hostname
or location.origin
上的data
事件来接收message
(只是一个典型的字符串):
window.addEventListener("message", callback);
大多数示例显示如何发送和接收消息,以及消息的结果显示在子页面lame上。如果它确实有用,这是一个回调:
function callback(event) {
var string = event.data;
// Optional-------------------------
var from = event.origin;
if (from !== 'https://www.example.com') {
document.querySelector('#displayMsg').textContent = `MESSAGE REJECTED`;
return;
}
//----------------------------------
if (string === "play") {
promisePlay();
} else if (string === "pause") {
document.querySelector('video').pause();
} else if (string === "stop") {
document.querySelector('video').pause();
document.querySelector('video').currentTime = 0;
} else {
document.querySelector('#displayMsg').textContent = `ERROR: ${string} is not a command.`;
}
}
注意:由于<iframe>
使用的SO限制,以下堆栈摘录无法正常运行。有关完整功能的演示,请转到此Plunker。
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
font: 400 16px/1.5 Consolas;
overflow: hidden;
}
main {
width: 100%;
height: auto;
padding: 10px;
}
section {
height: 0;
width: 100%;
position: relative;
padding-bottom: 56.25%;
margin: 15px auto 5px;
}
fieldset {
width: fit-content;
padding: 5px;
}
iframe {
height: 100%;
width: 100%;
overflow: hidden;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
select,
button {
font: inherit;
padding: 0 3px;
line-height: 1.2;
}
#msg {
position: absolute;
z-index: 1;
background: rgba(0, 0, 0, 0.5);
}
#time,
#rX {
display: block;
float: left;
color: gold;
padding: 0 5px;
width: 70px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Frame</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<section>
<iframe src="https://run.plnkr.co/preview/cjpwrvczh00073a5v3m08unmw/videoframe.html" width='100%' height='100%' scrolling='no' frameborder='0' allowfullscreen allow="autoplay; fullscreen"></iframe>
</section>
<form id='control'>
<fieldset>
<select id='tX'>
<option value='Timeslot'>Select</option>
<optgroup label='Command'>
<option>Play</option>
<option>Pause</option>
<option>Stop</option>
</optgroup>
<optgroup label='Load Media'>
<option>Video 1</option>
<option>Video 2</option>
<option>Video 3</option>
</optgroup>
<optgroup label="Test">
<option>Messages</option>
<option>Controls</option>
</optgroup>
</select>
<button>Send</button>
</fieldset>
</form>
</main>
<script>
window.onload = function(e) {
var ctrl = document.forms.control;
var cX = ctrl.elements;
var tX = cX.tX;
ctrl.addEventListener('submit', function(e) {
e.preventDefault();
window.frames[0].postMessage(tX.value, "https://" + location.hostname);
console.log(tX.value);
});
};
</script>
</body>
</html>
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
font: 400 16px/1.5 Consolas;
overflow: hidden;
}
main {
width: 100%;
height: auto;
padding: 10px;
}
section {
height: 0;
width: 100%;
position: relative;
padding-bottom: 56.25%;
margin: 15px auto 5px;
}
fieldset {
width: fit-content;
padding: 5px;
}
iframe {
height: 100%;
width: 100%;
overflow: hidden;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
select,
button {
font: inherit;
padding: 0 3px;
line-height: 1.2;
}
#msg {
position: absolute;
z-index: 1;
background: rgba(0, 0, 0, 0.5);
}
#time,
#rX {
display: block;
float: left;
color: gold;
padding: 0 5px;
width: 70px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video iframe</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<aside id='msg'>
<output id='rX'></output>
<time id='time'></time>
</aside>
<video id='vX' src='about:blank' width='96%' muted autoplay></video>
<script>
var v = document.getElementById('vX');
var vid =
'https://storage04.dropshots.com/photos6000/photos/1381926/20170326/';
var r = document.getElementById('rX');
var t = document.getElementById('time');
(function() {
loadVideo();
})();
window.addEventListener("message", rXMsg);
function rXMsg(e) {
var msg = e.data;
switch (msg) {
case 'Play':
playMedia();
break;
case 'Pause':
v.pause();
break;
case 'Stop':
v.pause();
v.currentTime = 0;
break;
case 'Video 1':
v.src = vid + '005609.mp4';
v.load();
break;
case 'Video 2':
v.src = vid + '005610.mp4';
v.load();
break;
case 'Video 3':
v.src = vid + '005612.mp4';
v.load();
break;
case 'Messages':
toggleAttr('#msg', 'hidden');
break;
case 'Controls':
toggleAttr('#vX', 'controls');
break;
default:
loadVideo();
break;
}
stamp(msg);
}
function loadVideo() {
var hrs = stamp();
// 05:00 - 09:59
if (hrs >= 5 && hrs < 10) {
v.src = vid + '005609.mp4';
v.load();
}
// 10:00 - 21:59
else if (hrs >= 10 && hrs < 22) {
v.src = vid + '005610.mp4';
v.load();
}
// 22:00 - 04:59
else {
v.src = vid + '005612.mp4';
v.load();
}
stamp('Autoload');
}
async function playMedia() {
try {
await v.play();
} catch (err) {
stamp('Promise Rejected');
}
}
function toggleAttr(selector, attr) {
var node = document.querySelector(selector);
var prop = node.getAttribute(attr);
if (!prop) {
node.setAttribute(attr, true);
} else {
node.removeAttribute(attr);
}
}
function stamp(str) {
var now = new Date();
var hrs = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
var h = hrs > 9 ? "" + hrs : "0" + hrs;
var m = min > 9 ? "" + min : "0" + min;
var s = sec > 9 ? "" + sec : "0" + sec;
var time = h + ":" + m + ":" + s;
r.textContent = str;
t.textContent = time;
return hrs;
}
</script>
</body>