Youtube sometimes doesn't play the Video - javascript

i have seen many post on SO there I got recommended to use mute. The problem is that from a list of embed urls, sometimes a video is not playing. I am hiding the iFrame and I think its because ads. So i came here to ask you guys, maybe you can help me to solve the problem.
HTML:
<iframe
src=""
width="500"
height="500"
frameborder="0"
class="youtube-player hidden"
allow="autoplay"
></iframe>
This function would be triggered every 15 sek
function changeElementOnWebpage() {
let soundtrackKey = ""
shows.forEach((showObj, index) => {
soundtrackKey = showObj.soundtrack
})
let ytURL = getSolidEmbedYTUrl(soundtrackKey)
document.querySelector(".youtube-player").src = ytURL
}
Generated URL by JS:
function getSolidEmbedYTUrl(soundtrackKey) {
return `https://www.youtube.com/embed/${soundtrackKey};autoplay=1&mute=0`
}
//https://www.youtube.com/embed/PtJ6yAGjsIs?start=0;end=15;autoplay=1&mute=0
My Datas where I pick the video.
const shows = [
{
soundtrack: "s7L2PVdrb_8?start=0;end=15",
},
{
soundtrack: "RcPZdihrp4?start=0;end=15",
},
{
soundtrack: "of-Bqmlgj98?start=0;end=15",
},
{
soundtrack: "8ZzVZs3C3kU?start=10;end=25",
},
{
soundtrack: "fBITGyJynfA?start=0;end=15",
},
If you need more information, please Ask.
Best Regards
Linda

Can I see your javescript code to? sorry that I ask this in a anwser but I don't have enough points to comment or something.

Related

Random ID on page load or Refresh

I'm trying to create a function that shows a different ID, on load or refresh/ A different video on load.
My main goal is to create a splash intro popup that shows a <section> with youtube video in full screen, As a Section with a video background.
I have 6 different videos and I want each time to load a different video.
So I'm doing this with Elementor.
adding 6 sections, giving each section an ID and inserting a different youtube video background.
I need to do something like document.getElementById('vidz')[0].className+=' add-' + Math.floor((Math.random() * 10) + 1);
I'm bad at JS Please help me.
I have this I want to add a function that shows each time a different ID: section#vidz1/#vidz2/#vidz3/.../#vidz6
and disables the other youtube videos to not load everything at once
function getRandomArrayItem(arr){
var randomKey = Math.floor(Math.random() * arr.length);
var item = arr[randomKey];
return(item);
}
function showRandomString(){
var arrKeys = ["first","second","third","four","five"];
var strItem = getRandomArrayItem(arrKeys);
document.getElementById("output").innerHTML = strItem;
}
window.onload = showRandomString;
If you have a better solution let me know each section loads the youtube
<iframe class="elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360" src="https://www.youtube.com/embed/qoXa-tTkitg" (more)></iframe>
So one section with a different youtube ID can be faster no?
Thanks
Any HTML in a <template> element is not rendered right away, so you could use that to avoid loading the videos. To keep this simple, you could just put the static content for a single <iframe> into the template and change it depending on the video data selected. For an example, see the snippet I've included below.
The following snippet doesn't run properly on this site, for some reason (assuming sandboxing). But, you can run the same code on jsfiddle and it does actually work.
// Interface w/ HTML
var SELECTORS = {
VIDEO_CONTAINER: '.js-video-container',
VIDEO_TEMPLATE: '.js-video-template',
VIDEO: '.js-video'
};
var VIDEO_DATA_LIST = [
{ src: 'https://www.youtube.com/embed/qoXa-tTkitg' },
{ src: 'https://www.youtube.com/embed/iphcyNWFD10' },
{ src: 'https://www.youtube.com/embed/IvUU8joBb1Q' },
{ src: 'https://www.youtube.com/embed/zGxwbhkDjZM' }
];
function getRandomArrayItem(array) {
return array[Math.floor(Math.random() * array.length)];
}
function insertRandomVideo(templateElement, parentElement, videoSelector, videoDataList) {
var videoData = getRandomArrayItem(videoDataList);
// Create a videoElement from the template
var videoElement = templateElement.content.cloneNode(true).querySelector(videoSelector);
// Add dynamic data to the cloned element
videoElement.src = videoData.src; // NOTE: videoData gets repeated if you use more properties
// Add the cloned element to the parent/container
parentElement.appendChild(videoElement);
}
window.addEventListener('DOMContentLoaded', function(event) {
// Run the function
insertRandomVideo(
document.querySelector(SELECTORS.VIDEO_TEMPLATE),
document.querySelector(SELECTORS.VIDEO_CONTAINER),
SELECTORS.VIDEO,
VIDEO_DATA_LIST
);
});
<div class="js-video-container"></div>
<template class="js-video-template">
<iframe class="js-video elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360"></iframe>
</template>
Also, here's an alternative version, which I like better. But, before you jump in, let me explain a few things I used, just in case you don't follow...
const is basically var (with different scoping but prevents re-assignment, so I like it for readability)
I used const with functions just to prevent them from being changed in later code.
I used arrow functions in place of "regular" functions - they prevent odd usage of this (when you don't actually NEED to use it in most cases) and I just personally like them because they're shorter.
I put all the selectors at top and made them include a js- prefix so it's easy to follow the hooks from HTML -> JS (also used this above, but added Object.freeze() to, again, prevent changes)
I used object destructuring just to keep things DRY when you add more properties to the video data objects.
Finally, I prefer to inject instead of directly using constants and elements inside a function
First, the jsfiddle, and here's the snippet:
// Interface w/ HTML
const SELECTORS = Object.freeze({
VIDEO_CONTAINER: '.js-video-container',
VIDEO_TEMPLATE: '.js-video-template',
VIDEO: '.js-video',
})
const VIDEO_DATA_LIST = [
{ src: 'https://www.youtube.com/embed/qoXa-tTkitg' },
{ src: 'https://www.youtube.com/embed/iphcyNWFD10' },
{ src: 'https://www.youtube.com/embed/IvUU8joBb1Q' },
{ src: 'https://www.youtube.com/embed/zGxwbhkDjZM' },
]
// (Just shortened this using arrow functions)
const getRandomArrayItem = array =>
array[Math.floor(Math.random() * array.length)]
const insertRandomVideo = (templateElement, parentElement, videoSelector, videoDataList) => {
const { src } = getRandomArrayItem(videoDataList)
// Create a videoElement from the template
const videoElement = templateElement.content.cloneNode(true).querySelector(videoSelector)
videoElement.src = src
// (Can also set other values if you include them in the data list)
parentElement.appendChild(videoElement)
}
window.addEventListener('DOMContentLoaded', event => {
// Run the function
insertRandomVideo(
document.querySelector(SELECTORS.VIDEO_TEMPLATE),
document.querySelector(SELECTORS.VIDEO_CONTAINER),
SELECTORS.VIDEO,
VIDEO_DATA_LIST,
)
})
<div class="js-video-container"></div>
<template class="js-video-template">
<iframe class="js-video elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360"></iframe>
</template>

VideoJS currentTime() always returning 0

I'm using videoJs to load a video into an admin
platform built in react. I set up the player here :
else if (contentSource == 'arclight'){
var options = {
height:'216',
sources :[{
//src: this.state.video.url,
// type: 'video/mp4'
}]
}
var player = videojs('player',options,function onPlayerReady() {
videojs.log('Your player is ready!');
})
this.setState({
player:player,content: contentSource
});
}
My video is displayed in this tag :
<video id="player" class="player"
className={`video-js vjs-default-skin vjs-big-play-centered
${styles.vjs}`}
controls preload= "auto" data-
setup='{"example_option":true}'>
<source src={this.state.video.url} type= "video/mp4" />
<p className="vjs-no-js">
To view this video please enable JavaScript, and consider
upgrading to a web browser that
<a href= "http://videojs.com/html5-video-support"
target="_blank"> supports HTML5 video </a>
</p>
</video>
and lastly i'm trying to get the current time of the video that is playing in this method
handleCurrentButton(inputId, event){
event.preventDefault();
var timeMark =0;
if(this.state.content == 'vimeo'){
this.state.player.getCurrentTime().then(function(seconds){console.log(seconds)
timeMark=seconds;
VideosActions.updateVideoAttribute(inputId, timeMark);
}).catch(function(error){
});
}
else if(this.state.content == 'youtube') {
timeMark = Math.round(this.state.player.getCurrentTime());
VideosActions.updateVideoAttribute(inputId, timeMark);
}
else {
// timeMark = this.state.player.currentTime();
console.log(this.state.player.currentTime())
VideosActions.updateVideoAttribute(inputId, timeMark);
}
}
the problem is that the player.currentTime() call is always returning 0. The other two getCurrentTime's for Vimeo and Youtube work fine. what is the reason behind this? I tried to give enough context around this problem so that you would be able to figure it out.
Thanks for your help in advance!
The problem is getCurrentTime() returns a promise so you need to access the value of the time when the promise is resolved as a callback to the Promise's .then() function.
else {
this.state.player.currentTime().then(function(seconds){
console.log(seconds)
timeMark=seconds;
VideosActions.updateVideoAttribute(inputId, timeMark);
});
}
Worth making sure your server returning 206 response on the video HTTP request, otherwise players dont handle seek well.

Trying to toggle a twitch player on/off using javascript in HTML

So I'm trying to learn some HTML5 stuff for making my own website from scratch. One thing I wanted to try was putting twitch chat and player in the web page. Iwant it to start the page with the player absent and the buttons available to be used to turn the player + chat on or off. Been trying to wrap my head around this and I can't find the solution I'm looking for. Would appreciate any tips or hints on how to do it, thanks!
Display/Hide Player
Display/Hide Chat
<script>
var playeron = false;
function player()
{
if(playeron==false)
{
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}
else
{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
var chaton=false;
function chat()
{
if(chaton==false)
{
chaton=true;
document.getElementById("MyChat").style.display="block";
}
else
{
chaton=false;
document.getElementById("MyChat").style.display="none";
}
}
</script>
<iframe id = "MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720"></iframe>
<iframe id = "MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720"></iframe>
<script>
var playeron=false;
var chaton=false;
function player(){
if(playeron==false){
playeron=true;
document.getElementById("MyPlayer").style.display="block";
}else{
playeron=false;
document.getElementById("MyPlayer").style.display="none";
}
}
//try it yourself for chat
</script>
Display/Hide player
Display/Hide Chat
<style>
iframe{
display:none;
}
</style>
you missed an opening bracket after function twitch(toggle)
Display/Hide Player
Display/Hide Chat
<iframe id="MyPlayer" src="https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147" width="1280" height="720" style="display: block;"></iframe>
<iframe id="MyChat" src="https://www.twitch.tv/blackdahlia1147/chat?popout=" width="300" height="720" style="display: block;"></iframe>
<script>
function toggle(id) {
var elem = document.getElementById(id);
if (elem.style.display != 'none') {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
}
</script>
This will work for you, with the advantage of flexibility if you want to make more things to hide/display.
I ran your code and I found that your trying to use variables with links in a if else loop. Now, what I'm saying is you created an option for a loop to search, which is good if you want to create multiple channels for a user to search.
else
{
player = "https://player.twitch.tv/?volume=0.32&channel=blackdahlia1147"
chat = "https://www.twitch.tv/blackdahlia1147/chat?popout="
}
what you first need to do is learn to add a "plugin" into your HTML if you want those two channels only. Your "player" and "chat" are links to a website, a "plugin" is what you're looking for. Go to youtube and type "plugin", when you get your "plugin" then write:
<iframe src="plugin"></iframe>
You really don't need the js at this point.
"Onclick" is what you're also looking for. Go to w3school.com and they have great options of buttons and animation options.

How to dynamically create multiple YouTube videos embedded to a page?

I was wondering if it is possible to create dynamically multiple YouTube embeds on a page. YouTube video id's where stored in a JSON object.
I was hoping something like this can be created dynamically by the script:
<iframe id="koW2Clc0xEA" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/koW2Clc0xEA?enablejsapi=1"></iframe>
I already use the YouTube JavaScript API to load one hero video, I can imagine that I may can use that code as the basic, but it belongs to another part of the site then the hero video.
I prepared a little JsFiddle for you: https://jsfiddle.net/v879x7bm/3/
Create a container in your HTML:
<div id="ytContainer"></div>
JavaScript with jQuery:
var yourJsonAsString = '{"videos":[{"title":"bla bla","id":"no3unQcv_vg"},{"title":"blub","id":"3IHrNcJdP8s"},{"title":"abc","id":"-6v-rwoRv_4"}]}';
var ytVideos = JSON.parse(yourJsonAsString);
for (var i in ytVideos.videos) {
var ytVideo = $("<iframe/>");
ytVideo.attr({
width: 560,
height: 315,
src: 'https://www.youtube.com/embed/' + ytVideos.videos[i].id,
frameborder: 0
});
$("#ytContainer").append(ytVideo);
}
In this example I expected your unserialized object structure is looking like this:
{
"videos":[
{
"title":"bla bla",
"id":"no3unQcv_vg"
},
{
"title":"blub",
"id":"3IHrNcJdP8s"
},
{
"title":"abc",
"id":"-6v-rwoRv_4"
}
]
}
But you can adapt to your needs :)
Imagine that your JSON string that contains the video urls. Here is some code that will work with jQuery. By changing the json_string variable, it will change which videos get loaded to the screen.
<html>
<div id="content_div"></div>
</html>
<script type="text/javascript">
jQuery(function () {
var json_string = '{ "vid1" : "www.vid1.url", "vid2" : "www.vid2.url"}';
//make the string into an object
var json_object = JSON.parse(json_string);
//loop through the json_object and add the new video each time through
for (i in json_object) {
jQuery("#content_div").append('<p><iframe width="420" height="315" src="' + json_object[i] + '"></iframe></p>');
}
});
</script>
JSfiddle here showing the code working, but using a <p> tag instead of the iframe.

New to Javascript, need help with HTML5 audio "playlist"

im trying to create a sort of playlist feature that will work on the iPhone using a combination of HTML5 and javascript. I'm very new to the platform and I was hoping maybe someone here could help me identify the problem with my code. The first song properly autoplays, but when it ends the next one does not load and play. The javascript code for my site is provided below, thanks in advance. (my apologies if this code is terribly messed up, i assembled this from what iv learned and what i could find different places online)
<script type="text/javascript">
var songname="Bottoms Up";
var counter=1;
var totalsongs=3;
while (counter<=totalsongs-1) {
document.write(<h2>songname</h2>);
switch (counter) {
case 1:
var nextSong="audio/Hey.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="Hey";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
case 2:
var nextSong="audio/I Like It.mp3";
var audioPlayer=document.getElementById('audioPlayer');
audioPlayer.onend = function() {
audioPlayer.src = nextSong;
songname="I Like It";
counter=(counter+1);
if(counter>totalsongs-1) {
counter=1;
} //if close
} //onend function close
} //switch close
} //while close
</script>
<center><audio src="audio/Bottoms Up.mp3" autoplay controls /></center>
A few things:
Give the audio element an id:
<audio src="audio/Bottoms Up.mp3" autoplay controls id="audioPlayer" /></center>
Use arrays instead of many variables:
var songs=({{"title": "First title","filename":"firstfile.mp3"},
{"title": "Second title","filename":"secondfile.mp3"}});
Listen for the event ended like this:
document.getElementById("audioPlayer").addEventListener("ended", nextSong, false);
And put the script in the <head> element.
var audioPlayer=document.getElementById('audioPlayer');
… will error, since the element doesn't have an id.

Categories

Resources