Create CSS overlay over youtube player to prevent clicking - javascript

I'm experimenting with embedding youtube videos, and am hoping to create a video that users can't interact with. I've managed to remove all the ui stuff, but can't seem to prevent clicking. I stumbled upon a website that is doing exactly what I want to do: on the bottom right, there is a youtube video with an apparent overlay that prevents clicking; it seems simple enough but I can't figure it out! Any advice would much appreciated. Here's my code so far:
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'BalUcQpYN6k',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>

You can simply add this to your css.
#player {pointer-events: none;}
#player {pointer-events: none;}
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'iRkCIuY2pHc',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>
I dont know how I ended up back here a year later but out of curious I went and looked up the OP's link and pointer-events: none is exactly what they are using, as shown below.
.player-container > .modal-inner-container > #player, .player-container > .modal-inner-container #html5-player, .lyrics-container > .modal-inner-container > #player, .lyrics-container > .modal-inner-container #html5-player {
pointer-events: none;
width: 100%;
height: 100%;
background-color: #000;

Update HTML with a bit more:
<div id="playArea">
<div id="player"></div>
<div class="yt-overlay"></div>
</div>
And add this CSS:
.yt-overlay, .#playArea > .yt-overlay {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1000;
}

Place a block element before the player. (#shield)
Next wrap both #shield and #player in a block element. (#main)
The important part is #main is position:relative and it's children elements are position:absolute with the overlay (#shield) having a higher z-index than the #player.
The rest of the Snippet should be self-explanatory.
SNIPPET
#main {
position: relative;
width: 400px;
height: 250px;
z-index: -1;
}
#shield {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
pointer-events: none;
cursor: not-allowed;
background: transparent;
}
#player {
position: absolute;
}
<!DOCTYPE html>
<html>
<body>
<main id='main'>
<section id='shield'></section>
<div id="player"></div>
</main>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'BalUcQpYN6k',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>

Related

How to make one button play several youtube videos in embedded iframes?

I have a few youtube videos embedded in a couple of iframes, and would like to start stop all the videos at once, using only one button. I've tried a few different methods, but just couldn't get it right.
Here is what I got.
main.html:
<!DOCTYPE html>
<html>
<head>
<title>YT Mosaic</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="container">
<div class="mosaic">
<iframe id="if1" src="https://www.youtube.com/embed/5mL-OkdM7Tc?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- TRT -->
<iframe id="if2" src="https://www.youtube.com/embed/9Auq9mYxFEE?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- SKY -->
<iframe id="if3" src="https://www.youtube.com/embed/VBTdNwm5CDY?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Global News -->
<iframe id="if4" src="https://www.youtube.com/embed/ntmPIzlkcJk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Euronews -->
<iframe id="if5" src="https://www.youtube.com/embed/GE_SfNVNyqk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- DW -->
<iframe id="if6" src="https://www.youtube.com/embed/h3MuIUNCCzI?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- F24 -->
</div>
<button onclick="iframe1play(); return false;">⏯️</button>
<button onclick="stop();">⏹</button>
<button onclick="playAll();">▶▶ Play All</button>
</div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var ifa = []; // array of iframe id's
var ifos = []; // array of iframe YT objects for use elsewhere
// For each iframe you find, add its ID to the ifa array
var iframes = document.querySelectorAll("div.mosaic iframe");
iframes.forEach(function(iframe) {
ifa.push(iframe.id);
});
console.log('[LOG] iframe array:', ifa)
// Array(6) [ "if1", "if2", "if3", "if4", "if5", "if6" ]
// Once the YouTube API is ready, for each iframeId in your array,
// create a new YT player and give it the onReady event.
function onYouTubeIframeAPIReady() {
ifa.forEach(function(iframeId) {
var player = new YT.Player(iframeId, {
events: {
'onReady': onPlayerReady,
}
});
});
}
function onPlayerReady(event) {
var ifo = event.target;
ifos.push(ifo); // Push current iframe object to ifo array
ifos.forEach(function(j) {
j.setVolume(30);
j.playVideo();
j.unMute();
});
}
var player;
// WARNING this need to be commented out as it interferes with the other version.
function onYouTubeIframeAPIReady() {
player = new YT.Player('if1', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000); // wait 6 s. before stopping player
done = true;
}
}
function catchError(event) {
if (event.data == 2) console.log("[LOG] Error: The request contains an invalid parameter value.");
if (event.data == 5) console.log("[LOG] Error: content cannot be played in an HTML5 player.");
if (event.data == 100) console.log("[LOG] Error: Video doesn't exists (or has been removed)!");
if (event.data == 101) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
if (event.data == 150) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
// This should never happen!
console.log("Error:\n", event);
}
// This was a test, not working, trying to use:
// onload="p1=new YT.Player(this);">
function playAll() {
var ifs = [p1,p2,p3,p4,p5,p6];
for(var i=0; i<ifs.length; i++) {
console.log("Try to Play: ", toString(ifs[i]));
ifs[i].playVideo();
}
}
function play() {
//player.unMute();
player.playVideo();
//show_video_url();
}
function pause() { player.pauseVideo(); }
function stop() { player.stopVideo(); }
function stopVideo() { player.stopVideo(); }
function mute() { player.unMute(); }
function iframe1play() {
if (player.getPlayerState() == YT.PlayerState.PLAYING) {
player.pauseVideo();
document.getElementById("if1").style.opacity = "0.7";
} else {
player.playVideo();
document.getElementById("if1").style.opacity = "1";
}
}
</script>
</body>
<footer>FTSE</footer>
</html>
and here is the CSS file main.css:
body {
background-color: #404040;
color: lightgrey;
margin: 0;
padding: 1em;
/*height: 100vh;*/
box-sizing: border-box;
}
.container {
max-width: 1100px;
/* width: 100%;*/
border: 1px solid black;
padding: 10px;
}
.mosaic {
display: grid;
/* Setup a 2x3 frame: */
/* fr is a fractional unit and 1fr is for 1 part of the available space */
grid-template-columns: 1fr 1fr;
grid-template-rows: 50% 50% 50%;
/*grid-template-rows: 1fr 1fr 1fr;*/
max-width: 1100px; /* 100% */
max-height: 100%; /* 100% */
/*aspect-ratio: 16/9;*/ /* 16/9 */
/* margin: auto; */ /* auto */
margin-bottom: 1em; /* 1em */
/*padding: 2em; */
gap: 5px; /* 1em */
}
iframe {
/* iframe width="560" height="315" */
display: block;
width: 100%;
height: 100%;
aspect-ratio: 16/9; /* */
/*min-width: 350px;*/ /* 350px */
/*min-height: 200px;*/ /* 200px */
background: gray; /* yellow */
border: 1px solid black; /* border: solid red */
margin: 0px; /* */
}
How can I use the iframe id= tag to start all iframe videos using one button?
preferably using JS without additional libraries, such as jQuery.
JSfiddle code
You can use Youtube's IFrame Player API. They have a great documentation here https://developers.google.com/youtube/iframe_api_reference
You can basically control all youtube embed videos by generating it through their API.
A working sample would be down below:
<body>
<div id="container">
<div id="player-5mL-OkdM7Tc"></div> <!-- TRT -->
<div id="player-9Auq9mYxFEE"></div> <!-- SKY -->
<div id="player-VBTdNwm5CDY"></div> <!-- Global News -->
<div id="player-ntmPIzlkcJk"></div> <!-- Euronews -->
<div id="player-GE_SfNVNyqk"></div> <!-- DW -->
<div id="player-h3MuIUNCCzI"></div> <!-- F24 -->
</div>
<button onclick="play()">
Play All
</button>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="main.js" async defer></script>
</body>
let playersObjs = [];
window.onYouTubeIframeAPIReady = () => {
const playerContainers = document.querySelectorAll('div[id^="player"]');
playerContainers.forEach((container) => {
const videoId = container.id.slice(7);
playersObjs.push(new YT.Player(container.id, {
height: '200',
width: '100',
videoId,
playerVars: {
'playsinline': 1
}
}))
})
}
const play = () => {
playersObjs.forEach((player) => {
player.playVideo();
})
}

Turn background video (ambient video) into a playable video on button click

I have created an iframe by taking advantage of YouTube's API.
On page load, the ambient video is set to autoplay with no sound. However, on top of the div which contains the iframe, I have a button.
On this button click, I want the video to reset (start from the beginning) with the YouTube controls and sound on - similar to the one in the hero here: https://www.hugeinc.com/work.
Wondering how I would go about this? Would it involve creating another iframe?
Not looking to do this as a modal pop-up
Code:
// Load IFrame Player API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Creating iframe
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'jagIsKF8oVA',
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1,
'rel': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// Calls function
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
// if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
// done = true;
// }
}
function stopVideo() {
// player.stopVideo();
}
<!-- THIS IS IN home.php-->
<button>Click me</button>
<!-- THIS IS IN hero.php -->
<section id="videoHero" class="hero hero--video">
<div class="hero__container--teaser">
<!-- Where the iframe is stored-->
<div id="player"></div>
</div>
</section>
Not looking to do this as a modal pop-up. Similar to the functionality here: https://www.hugeinc.com/work (play button on hero is clicked, video resets and plays from the start with controls at the bottom).
I used another iframe because there is no method to change the controls display you may check https://developers.google.com/youtube/iframe_api_reference for more information or you can do console.log(player) and ckeck all the methods.
I used
contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
to stop the iframe and
contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
to restart it also for this two line of code to work I added &enablejsapi=1 to the iframe src
also I used the YouTube Player API for the muted video so that it will loop whiteout refresh (in case of not using the YouTube Player API for the video to loop you need to add to the src of the iframe playlist=videoId&loop=1 and this will make the iframe refresh when the video end)
I haven't added showinfo=0 to the muted video because it is deprecated and will be ignored after September 25, 2018.
you may check https://developers.google.com/youtube/player_parameters#showinfo for more info
Lastly the snippet doesn't work . you need to make local html file or delete sandbox from the sinppet iframe then click on Run code snippet a second time
var modalTeaser = document.getElementById('hero__container--teaser');
var btn = document.getElementById("myBtn");
var iframe = document.getElementById("iframe");
var span = document.getElementsByClassName("close")[0];
var videoId = '88xPxULx-II';
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('iframe', {
videoId: videoId,
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data === YT.PlayerState.ENDED) {
player.playVideo();
}
}
var video = document.createElement('iframe');
video.className = "ply";
modalTeaser.prepend(video);
video.style.display = 'none';
video.src = "https://www.youtube.com/embed/"+videoId+"?enablejsapi=1";
video.setAttribute('frameborder', "0");
btn.onclick = function() {
iframe.style.display = "none";
video.style.display = "block";
btn.style.display = "none";
span.style.display = "block";
video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
}
span.onclick = function() {
iframe.style.display = "block";
video.style.display = "none";
btn.style.display = "block";
span.style.display = "none";
video.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
}
body {
margin: 0;
}
.close{
z-index: 10;
position: relative;
display: none;
}
.ply{
z-index: 2 !important;
}
#videoHero {
position: relative;
padding-bottom: calc((544 / 1280) * 100%);
background-color: rgba(255, 0, 0, .1)
}
.hero__container--teaser {
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
.modal{
width: 80%;
height: 80%;
background-color: black;
}
/* Having the following on the iframe moves the iframe out of the div (and visual). Not having them puts
the iframe in the div, but not full width not height of #videoHero*/
#player,
iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -10;
}
#myBtn {
position: absolute;
top: 80px;
left: 300px;
z-index: 10;
width: 100px;
height: 100px;
background-color: red;
}
.modal {
display: none;
position: fixed;
z-index: 122;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.modal-content {
z-index: 400;
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
<section id="videoHero" class="hero hero--video">
<button type="button" class="close" data-dismiss="modal" aria- label="Close">
<span aria-hidden="true">×</span>
</button>
<div id="hero__container--teaser" class="hero__container--teaser">
<!-- #player is where the iframe is-->
<div id="iframe" ></div>
</div>
<button id="myBtn">Start video</button>
</section>

How to play/start vimeo video after clicking on an image?

I have some code, that works good with youtube videos, but I need the same effect with vimeo videos, wondering how to do this, any suggestions? Need replace youtube discription by vimeo but I don't know how to do this.
P.S Sorry for my English...
<style type="text/css">
#head {
background-color:transparent;
width:100%;
}
#container {
cursor:pointer;
width:520px;
height:380px;
}
.inactive-state {
background-repeat: no-repeat;
background-size: 100%;
background-image: url();
}
.hover-state {
background-image: url();
}
</style>
<section id="head">
<div id="container" class="click-to-play-video inactive-state">
<div id="player" class="home-player"></div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$("#container").mouseenter(function () {
$(this).addClass('hover-state');
}).mouseleave(function () {
$(this).removeClass('hover-state');
});
$("#container.click-to-play-video").click(function () {
$('#head').css({ "background-color": "transparent" });
player = new YT.Player('player', {
width: '520',
height: '300',
videoId: 'qlEUrEVqDbo',
playerVars: { 'autoplay': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onPlayerReady(event) {
//event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
player.destroy();
$('#head').css({ "background-color": "transparent" });
}
}
</script>
In it's most simple form, you'll want something like this. Just remove the image and append the iframe, with autoplay on.
$('.vimeo-img').click(function (event) {
var $this = $(this),
$parent = $this.parent();
$this.remove();
$parent().append('<iframe src="..." autoplay="true"></iframe>');
})

How to create valid preloader with jQuery, which can preload mp3 file to browser cache?

I have a simple drawing spectrum on a website http://alldev.eu/html/mp3/index.phtml, which loads to browser cache a song and plays it after it's fully downloaded.
I've made a pre-loader for my site which displays a message and an image for 7 seconds while the song is being loaded. Unfortunately, it doesn't work in the way I'd like to since 7 seconds might not be enough time to load a song (for instance, a test song with 11 Megabytes)
How can I rebuild my site to pre-load all data? My current script is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>Shiny Toy Guns - Major Tom</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.extend({
jqbar: function(options) {
var DefaultSpeedOfAnimation = 7000;
var settings = $.extend({
SpeedOfAnimation: DefaultSpeedOfAnimation,
LengthOfBar: 200,
barWidth: 10,
barColor: 'red',
label: ' ',
value: 100
}, options);
return this.each(function() {
var valueLabelHeight = 0;
var ContainerProgress = $(this);
ContainerProgress.addClass('jqbar horizontal').append('<div class="bar-label"></div><div class="bar-level-wrapper"><div class="bar-level"></div></div><div class="bar-percent"></div>');
var progressLabel = ContainerProgress.find('.bar-label').html(settings.label);
var progressBar = ContainerProgress.find('.bar-level').attr('data-value', settings.value);
var progressBarWrapper = ContainerProgress.find('.bar-level-wrapper');
progressBar.css({
height: settings.barWidth,
width: 0,
backgroundColor: settings.barColor
});
var valueLabel = ContainerProgress.find('.bar-percent');
valueLabel.html('0');
animateProgressBar(progressBar);
function animateProgressBar(progressBar) {
var level = parseInt(progressBar.attr('data-value'));
if (level > 100) {
level = 100;
alert('max value cannot exceed 100 percent');
}
var w = settings.LengthOfBar * level / 100;
progressBar.animate({
width: w
}, {
duration: DefaultSpeedOfAnimation,
step: function(currentWidth) {
var percent = parseInt(currentWidth / settings.LengthOfBar * 100);
if (isNaN(percent)) percent = 0;
ContainerProgress.find('.bar-percent').html(percent + '%');
}
});
}
});
}
});
})(jQuery);
</script>
<style>
body {
text-align: center;
background-color: black;
color: white;
}
footer {
float: center;
bottom: 0;
position: absolute;
color: #FFFFFF;
font: bold 1.2em/2.5 arial;
width: 99%;
}
.jqbar {
position: relative;
top: 100px;
}
.jqbar.horizontal div {
display: inline-block;
margin-left: 5px;
font-size: 11px;
font-weight: bold;
}
.jqbar.horizontal .bar-percent {
font-size: 11px;
font-weight: bold;
height: 20px;
margin-bottom: 5px;
}
#progressbar {
width: 400px;
height: 22px;
border: 1px solid #000;
background-color: #292929;
}
#progressbar div {
height: 100%;
color: #FFF;
text-align: center;
line-height: 22px;
width: 0;
background-color: #0099FF;
}
#preloader {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
color: #FFF;
z-index: 99;
height: 100%;
}
#status {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
background-color: #000;
background-repeat: no-repeat;
background-position: center;
margin: -100px 0 0 -100px;
}
</style>
</head>
<body onload="hide_preloader();">
<div id="preloader">
<div id="status">Wait for MP3 Load...
<br>
<br>
<br>
<img src="http://alldev.eu/html/images/Loader.gif" />
</div>
</div>
<footer>
<center>
<div id="bar-1"></div>
<canvas id="music" width="1024" height="250" style="display: block;"></canvas>
</center>
</footer>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery("#status").delay(5000).fadeOut(2500);
jQuery("#preloader").delay(5000).fadeOut(2500);
jQuery("#bar-1").delay(5000).fadeOut(2500);
});
$(document).ready(function() {
$('#bar-1').jqbar({
SpeedOfAnimation: 7000,
label: 'Loading...',
value: 100,
barColor: '#FFF',
barWidth: 20
});
});
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert('AudioContext not found!');
}
window.AudioContext = window.webkitAudioContext;
}
var context = new AudioContext();
var audioBuffer;
var sourceNode;
var analyser;
var javascriptNode;
var ctx = $("#music").get()[0].getContext("2d");
var gradient = ctx.createLinearGradient(0, 0, 0, 325);
gradient.addColorStop(1, '#FFFFFF');
gradient.addColorStop(0.75, '#00FFFF');
gradient.addColorStop(0.25, '#0000FF');
gradient.addColorStop(0, '#000000');
setupAudioNodes();
loadSound("http://alldev.eu/html/mp3/Shiny%20Toy%20Guns%20-%20Major%20Tom%20(Official%20Live).mp3");
function setupAudioNodes() {
javascriptNode = context.createScriptProcessor(2048, 1, 1);
javascriptNode.connect(context.destination);
analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.75; //0.5;
analyser.fftSize = 512;
sourceNode = context.createBufferSource();
sourceNode.connect(analyser);
analyser.connect(javascriptNode);
sourceNode.connect(context.destination);
}
$(document).ready(function() {
$.ajax({
url: "soundfile.mp3",
success: function() {
$("#play_button").show();
}
});
});
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
playSound(buffer);
}, onError);
}
request.send();
}
function playSound(buffer) {
sourceNode.buffer = buffer;
sourceNode.start(0);
}
function onError(e) {
console.log(e);
}
javascriptNode.onaudioprocess = function() {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
ctx.clearRect(0, 0, 1024, 325);
ctx.fillStyle = gradient;
drawSpectrum(array);
}
function drawSpectrum(array) {
for (var i = 0; i < (array.length); i++) {
var value = array[i];
ctx.fillRect(i * 5, 325 - value, 3, 325);
}
};
</script>
</body>
</html>
you can give preloadJS a try.
http://www.createjs.com/#!/PreloadJS
here's some code from their documentation to get you started:
var queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.on("complete", handleComplete, this);
queue.loadFile({id:"sound", src:"http://path/to/sound.mp3"});
queue.loadManifest([
{id: "myImage", src:"path/to/myImage.jpg"}
]);
function handleComplete() {
createjs.Sound.play("sound");
var image = queue.getResult("myImage");
document.body.appendChild(image);
}
Check for JWPlayer API, you can have access to a method getBuffer(), which returns the current buffered state for your audio file : http://www.longtailvideo.com/support/jw-player/28851/javascript-api-reference/
But this requires to use JWplayer to play / handle your audio file, as it's not included in the audio object : http://www.w3schools.com/tags/av_prop_buffered.asp
EDIT :
I took some time to make it work, see the fiddle :) : http://jsfiddle.net/uKZ8N/
Basically, I set an interval of 0,5s which check the getBuffer() value.

Youtube iframe api under Google Chroome mobile browser

Hi I used iframe api to create yt movie player.I encountered problem on Google chrome for mobile. To start movie i used playVideo() function. I see that movie is loading but after that i see nothing more than black yt player with no sound. I tested it on my pc computer, Google Chrome for mobile, my colleague iPhone 4s and even on my HTC Wildfire S with native browser. Everything was fine.
Example
To create movie:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1, player2, player3;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('ytapiplayer1', {
height: '390',
width: '640',
videoId: 'Vhik235dWLk',
});
player2 = new YT.Player('ytapiplayer2', {
height: '390',
width: '640',
videoId: 'p_Y5WjjVb9I',
});
player3 = new YT.Player('ytapiplayer3', {
height: '390',
width: '640',
videoId: '6HOo7_NNHu4',
});
}
HTML:
<div id="owl-example" class="owl-carousel">
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/Vhik235dWLk/0.jpg)">
<div id="ytapiplayer1"></div>
</div>
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/p_Y5WjjVb9I/0.jpg)">
<div id="ytapiplayer2"></div>
</div>
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/6HOo7_NNHu4/0.jpg)">
<div id="ytapiplayer3"></div>
</div>
</div>
CSS:
.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px; height: 0; overflow: hidden;
background-repeat: no-repeat;
background-position: center center;
background-size: 100%;
}
.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
JS to start owl carousel and play, stop movie
$(document).ready(function() {
$("#owl-example").owlCarousel({
singleItem : true,
afterMove: function(){
$('.video-container').css('background-position', 'center')
$('iframe').hide();
player1.stopVideo();
player2.stopVideo();
player3.stopVideo();
}
});
$('body').on('click', '.video-container', function(){
var owl = $(".owl-carousel").data('owlCarousel');
console.log(owl.currentSlide)
if (owl.currentSlide == 0){
player1.playVideo()
}
if (owl.currentSlide == 1){
player2.playVideo()
}
if (owl.currentSlide == 2){
player3.playVideo()
}
$(this).css('background-position', '-1000px -1000px');
$(this).find('iframe').show()
});
});

Categories

Resources