I want to play video and audio in autoplay mode, When both are ready to play. I'm using this code.
var player;
player = new YT.Player('YouTubeVideoPlayer', {
videoId: 'ID', // YouTube Video ID
width: 560, // Player width (in px)
height: 316,
start:0, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 0, // Show pause/play buttons in player
showinfo: 0, // Show pause/play buttons in player
rel: 0, // Hide the video title
modestbranding: 0, // Hide the Youtube Logo
loop: 0, // Run the video in a loop
fs: 1, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
autohide: 1 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.setVolume(100);
}
}
});
}
This code is working fine in desktop browsers. But when I try it on mobile device it is not working.
I had already given up, until I found this page. It works on both Mobile and Chrome. The question is, how?
Page: https://neilpatel.com/br/master-class/?v=noredirect
Related
I am trying to make a custom youtube playlist based on the example here.
However, the youtube player gets "jammed" and skips videos (in my case the middle video is skipped). The code is supposed to iterate through the arrays below and play one video at a time with each video having separate start/end times.
How would one go about making this work properly. (note that the code below needs to be uploaded to a website to work. Apparently from a local computer, it does not work)
Here is the code I am using:
<html>
<body>
<div id="ytplayer"></div>
<script>// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var i = 0;
var videoId_arr = ['O57DyNMRGY8','-Yh2QGJBd2U','M7lc1UVf-VE'];
var startSeconds_arr = [41,26,17];
var endSeconds_arr = [50,40,30];
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
var playerConfig = {
height: '360',
width: '640',
videoId: videoId_arr[i],
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 1, // Hide the video title
modestbranding: 0, // Hide the Youtube Logo
fs: 1, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
start: startSeconds_arr[i],
end: endSeconds_arr[i],
autohide: 0, // Hide video controls when playing
},
events: {
'onStateChange': onStateChange
}
};
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', playerConfig);
}
function onStateChange(state) {
if (state.data === YT.PlayerState.ENDED) {
i++;
if(typeof videoId_arr[i] === 'undefined')
return;
player.loadVideoById({
videoId: videoId_arr[i],
startSeconds: startSeconds_arr[i],
endSeconds: endSeconds_arr[i]
});
}
}
</script>
</body>
</html>
I have tested your code and I figured out that the state is changing for some unknown reasons very quickly. The state has sometimes the value 0 which equals YT.PlayerState.ENDED although the video was not played.
You can see it by console logging state.data within the onStateChange function.
A small change fixed the problem:
function onStateChange(state) {
var _video_url = state.target.getVideoUrl();
var _video_id = _url.split('v=')[1];
var _current_index = videoId_arr.indexOf(_video_id) +1;
console.log('State: ', _video_id, _current_index, state );
// ensure that the video has been played
if (state.data === YT.PlayerState.ENDED && player.getCurrentTime() >= endSeconds_arr[i]) {
i++;
if(typeof videoId_arr[i] === 'undefined'){
i = 0; // rest the counter
return;
}
}
}
For the code to run properly you should disable browser plugins like Video Resumer or similar - since they can change the state of a youtube video or resumes the videos from where you stopped them last
fiddle: https://jsfiddle.net/_kdts/Lx91ehdw/
I it possible to loop the videos? I was trying by changing i=1
if(typeof videoId_arr[i] === 'undefined'){
i = 1; // rest the counter
return;
}
I am using Angular-cli. I'd like to utilize the youtube iframe api within an Angular2 module. I couldn't get the youtube-iframe node package to work. And the more Angular2 specific packages don't seem to support the full api features.
Here's my work so far:
I have included the actual api in my assets folder. I have added the location as a script within my .angular-cli.json file.
This is what my AppComponent looks like:
export class AppComponent {
YT;
constructor(){
this.YT = window["YT"];
}
onYouTubeIframeAPIReady() {
console.log(this.YT);
var player;
player = new this.YT.Player('muteYouTubeVideoPlayer', {
videoId: 'KKYYAbGpw6A', // YouTube Video ID
width: 560, // Player width (in px)
height: 316, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 0, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 0, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 0, // Hide the Video Annotations
autohide: 1 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
ngAfterViewInit(){
this.onYouTubeIframeAPIReady();
}
It works when I have the devTools open in Chrome. But not when I have them closed. This is the error I get:
this.YT.Player is not a constructor
at AppComponent.webpackJsonp.328.AppComponent.onYouTubeIframeAPIReady
I guess the problem is using window["YT"]. Can anyone provide me with a step by step guide of doing this properly?
This should be a timing issue. For the onYouTubeIframeAPIReady, It is a youtube provided callback. So inside ngOninit() or ngAfterViewInit(), I would recommend you register it at the window level to let youtube API call it when everything is ready.
something like:
(<any>window).onYouTubeIframeAPIReady = ()=>{
console.log((<any>window).YT);
this.player = new (<any>window).YT.Player('muteYouTubeVideoPlayer', {
videoId: 'KKYYAbGpw6A', // YouTube Video ID
width: 560, // Player width (in px)
height: 316, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 0, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 0, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 0, // Hide the Video Annotations
autohide: 1 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
Currently, I'm using this jquery which gets youtube video and plays them in element's background.
I was provided with this code that will play single youtube video. But I would like to make a list of videos and play them randomly... I am not so good with Javascript at the moment, so I would really appreciated some help on this...
right now I have this....
I wanna make a list of videos and play them randomly like a shuffled playlist..
$(function()
{
var videos = ['xJvt2SDV7ck', 'x6DD1k4BAUg', 'xJvt2SDV7ck'];
var index = Math.floor(Math.random() * videos.length);
var Video_back = new video_background($("#bgvideo"),
{
"position": "absolute", //Stick within the div
"z-index": "-1", //Behind everything
"loop": true, //Loop when it reaches the end
"autoplay": true, //Autoplay at start
"muted": true, //Muted at start
"youtube": "videos[index]", //Youtube video id
"start": 0, //Start with 6 seconds offset (to pass the introduction in this case for example)
"video_ratio": 1.333, // width/height -> If none provided sizing of the video is set to adjust
"fallback_image": "videos/main.jpg", //Fallback image path
});
});
Currently It only plays 1 video randomly selected from the list(single loop).
I want to make it so that it will move on to another video when the first video finishes..
HELP WILL BE MUCH MUCH APPRECIATED! THANK YOU FOR YOUR TIME!
The following answer is based on the fact that there is no way of determining when a video has finished. The lengths are in milliseconds:
$(function()
{
var videos =
[
{ id : 'xJvt2SDV7ck', length : 60000 },
{ id : 'x6DD1k4BAUg', length : 125000 },
{ id : 'xJvt2SDV7ck', length : 166000 }
];
function playNext()
{
var index = Math.floor(Math.random() * videos.length);
alert( "Playing next movie => " + videos[index].id );
var Video_back = new video_background($("#bgvideo"),
{
"position": "absolute", //Stick within the div
"z-index": "-1", //Behind everything
"loop": true, //Loop when it reaches the end
"autoplay": true, //Autoplay at start
"muted": true, //Muted at start
"youtube": videos[index].id, //Youtube video id
"start": 0, //Start with 6 seconds offset (to pass the introduction in this case for example)
"video_ratio": 1.333, // width/height -> If none provided sizing of the video is set to adjust
"fallback_image": "videos/main.jpg", //Fallback image path
});
setTimeout(function()
{
playNext();
}, videos[index].length);
}
playNext();
});
How can I embed different YouTube videos at different places on the page using YouTube API? (This means they can not share the same <div> "player".) They also start at different times based on different onclick events. My code works fine when only one video is on the page, but for the life of me I cannot figure out the code to let this all work with 2 or more!
At first I was trying to simply add multiple instances of the code where I wanted each one to be, but that wasn't working. I read that all the players need to be added to one <script>, so I tried this:
(Also, does it matter WHERE on the page the <script> is and where the <div>s are? Can the <script> write to a <div> no matter where they are on the page?)
Anyway, here's the code I'm using:
// inside other containers with with relative and absolute positioning
// that fadeIn and fadeOut using jQuery
<div id="video1"></div>
// inside other containers with with relative and absolute positioning
// that fadeIn and fadeOut using jQuery
<div id="video2"></div>
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('video1',{
width: '320',
height: '216',
videoId: 'VIDEO_ID_1',
playerVars: {rel: 0, controls: 0, autohide: 1, disablekb: 1, enablejsapi: 1, modestbranding: 1, showinfo: 0 },
events: { 'onStateChange': onPlayerStateChange1 } });;
player2 = new YT.Player('video2',{
width: '320',
height: '216',
videoId: 'VIDEO_ID_2',
playerVars: {rel: 0, controls: 0, autohide: 1, disablekb: 1, enablejsapi: 1, modestbranding: 1, showinfo: 0 },
events: { 'onStateChange': onPlayerStateChange2 } });; }
function startVideo1() {
player1.playVideo();
$('#video_box_B1').delay(1000).fadeIn();
$("#video_box_B1").delay(20000).hide();
};
function onPlayerStateChange1(event) {
if(event.data === 2) {
$("#video_box_B1").hide();
}
}
function startVideo2() {
player2.playVideo();
$('#video_box_E5').delay(1000).fadeIn();
$("#video_box_E5").delay(20000).hide();
};
function onPlayerStateChange2(event) {
if(event.data === 2) {
$("#video_box_E5").hide();
}
}
</script>
// onclick triggers at various places on the page
<img src="image_1.jpg" onclick="startVideo1()" />
<img src="image_2.jpg" onclick="startVideo2()" />
Is there anyone who can tell what I'm doing wrong? BTW, those containers fading in and out works perfectly if I'm using a still image, text-only, or with only one video on the page, so it's not those fading containers causing this. It's got to be the YouTube script. Can anyone help?
Seems to be working in this jsbin:
http://jsbin.com/catuhimo/3/edit
What browser are you trying it out in? If you're using Safari bleeding edge Version 8.0 (10538.39.41) on Yosemite, jsfiddle and jsBin had some trouble rendering things. I tried out your code on Chrome latest and replaced the placeholders with actual video IDs and it worked.
Does that help? Am I missing the point of the your question? Based on what you asked, it seems to work ok for me.
how to make the JW Player have a "resume" or "remember" function which marks position of last
play position of movie and remembers it when you come back to watch video again? So, if a
viewer stopped watching a movie at 36:25 minutes on a 2 hour movie and had to go offline, when
they returned to watch movie, the JW player would open to the correct position and "resume"
play.
This should get you started:
http://osric.com/chris/jwplayer/jwplayer5.4/ontime.html
The JavaScript from that page is as follows:
$(document).ready( function() {
jwplayer("container").setup({
file:"playlist.xml",
height: 300,
width: 400,
events: {
onTime: function(event) {
$('#timer').html(Math.floor(event.position));
}
}
});
That code sets an element with the id of "timer" to be the value of the current position.
You could then create either a cookie to save the variable from the JS.
Edit
You can use this link to help with the cookie function:
http://www.w3schools.com/js/js_cookies.asp
$(document).ready( function() {
jwplayer("container").setup({
file:"playlist.xml",
height: 300,
width: 400,
events: {
onPause: function(event) {
setCookie(event.position);
}
}
});