HTML5 - Fire event every few seconds while video is playing - javascript

I want to track user engagement for a video, by tracking how many users are dropping of at different time interval.
For this I need to fire a tracking event, every 15 seconds while the video is playing.
The playing event is triggered once. I need something which I can use throughout the life of the video.
var _video = $('video')[0],
timeoutID;
$(_video).on('playing', function(event){
timeoutID = window.setTimeout(function() {
console.log("video is playing");
}, 15000);
}).on('ended', function(event){
console.log("video eneded");
window.clearTimeout(timeoutID);
});

You can use the timeupdate event instead, it updates whenever the video's currentTime changes, or in other words it updates as the video is playing and gives you the amount of video the user has actually seen
var _video = $('video')[0];
$(_video).on('timeupdate', function() {
var hasPlayedTime = _video.currentTime;
});
var _video = $('video')[0];
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
$('#result').html('<strong>Elapsed : </strong>' + hasPlayedTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video controls="" style="width:240px;height:180px;">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: -100px; left: 20px"></span>
To act only every fifteen seconds on an event such as that, we need to add some math and logic
var _video = $('video')[0],
debounce = true,
seconds = 5; // set to 15 instead
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
var intPlayedTime = parseInt(hasPlayedTime, 10);
var isFifteen = intPlayedTime % seconds === 0 && intPlayedTime !== 0;
if (isFifteen && debounce) {
debounce = false;
$('#result span').html(intPlayedTime);
} else {
setTimeout(function() {
debounce = true;
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" controls="controls"></script>
<video controls="" style="width:240px;height:180px; position: relative; top: -20px; float:left">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: 70px; left: 20px">
<p><u>Updates every five seconds</u></p>
<strong>Elapsed : </strong>
<span>0</span>
</span>

use window.setInterval instead of window.setTimeout
$(_video).on('playing', function(event){
timeoutID = window.setInterval(function() {
console.log("video is playing");
}, 15000);
}).on('ended', function(event){
console.log("video eneded");
window.clearInterval(timeoutID);
});

I did this
var lastSecond = null;
var secondsToCallFunction = 20;
$(_video).on('timeupdate', function(e) {
var seconds = Math.floor(e.target.currentTime);
if (seconds % secondsToCallFunction == 0 && lastSecond !== seconds) {
lastSecond = seconds
console.log(seconds);
}
});

Related

Play video in loop with different timing and function

I have 2 function which play the same video but with different timing.
I can't play make the function to work properly.
Looks like the function doesn't reset the other function
I tried to change variables names but still change the timing on click.
var video = document.getElementById('videoElm');
function playShortVideo() {
var starttime = 0; // start at 0 seconds
var endtime = 2; // stop at 2 seconds
video.addEventListener("timeupdate", function() {
if (this.currentTime >= endtime) {
this.currentTime = 0; // change time index here
}
}, false);
video.load();
video.play();
}
function playFullVideo() {
var starttime = 0; // start at 0 seconds
var endtime = 24; // stop at 2 seconds
video.addEventListener("timeupdate", function() {
if (this.currentTime >= endtime) {
this.currentTime = 0; // change time index here
}
}, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>
That's because the listener is still there, you need to remove it.
Remember, in order to remove it, you can't use anonymous function as callback so I turned it into defined function.
var video = document.getElementById('videoElm');
const playShort = function() {
if (this.currentTime >= 2) {
this.currentTime = 0; // change time index here
}
};
const playFull = function() {
if (this.currentTime >= 24) {
this.currentTime = 0; // change time index here
}
};
function playShortVideo() {
video.removeEventListener("timeupdate", playFull, false)
video.addEventListener("timeupdate", playShort, false);
video.load();
video.play();
}
function playFullVideo() {
video.removeEventListener("timeupdate", playShort, false)
video.addEventListener("timeupdate", playFull, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>
And here is the approach for starting the video at 49 sec (60 > 49 + 10)
const shortStartTime = 49;
const shortDuration = 10;
var video = document.getElementById('videoElm');
const playShort = function() {
if (this.currentTime > (shortStartTime + shortDuration)) {
this.currentTime = shortStartTime; // change time index here
}
};
const playFull = function() {
if (this.currentTime >= 24) {
this.currentTime = 0; // change time index here
}
};
function playShortVideo() {
video.removeEventListener("timeupdate", playFull, false)
video.addEventListener("timeupdate", playShort, false);
video.load();
video.currentTime = shortStartTime;
video.play();
}
function playFullVideo() {
video.removeEventListener("timeupdate", playShort, false)
video.addEventListener("timeupdate", playFull, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>
That happens because you're attaching a timeUpdate event listener multiple times.
You either need to use one-only or delete it before attaching a new one.
var video = document.getElementById('videoElm');
var listener;
var starttime = 0;
var endtime = 2;
function updateVideo(e) {
if (e.target.currentTime >= endtime) {
e.target.currentTime = 0; // change time index here
}
}
function playShortVideo() {
starttime = 0; // start at 0 seconds
endtime = 2; // stop at 2 seconds
if (!listener) {
listener = video.addEventListener("timeupdate", updateVideo, false);
}
video.load();
video.play();
}
function playFullVideo() {
starttime = 0; // start at 0 seconds
endtime = 24; // stop at 2 seconds
if (!listener) {
listener = video.addEventListener("timeupdate", updateVideo, false);
}
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>

Unable to play one array of videos for an hour

I have array of multiple videos. Right now, the code below works in that it plays multiple videos one after the other. However, they are time agnostic, and I specifically want to play these videos for exactly one hour. How can I achieve this using Javascript?
<body onload="myNewSrc()">
<div id="section-title">
<video onended="myAddListener()" autoplay controls width="100%" height="auto">
<source src="" type="video/mp4">
</video>
</div>
<script>
var videoSources = ["http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
"http://www.html5videoplayer.net/videos/toystory.mp4",
"http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
"http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
"http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"
];
var currentIndex = 0;
//listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = videoSources[currentIndex];
myVideo.load();
}
function myAddListener() {
var myVideo = document.getElementsByTagName('video')[0];
currentIndex = (currentIndex + 1) % videoSources.length;
myVideo.src = videoSources[currentIndex];
myVideo.addEventListener('ended', myNewSrc, false);
}
</script>
</body>
Add a DOMContentLoaded event listener to body, then inside that get the current time using Date.now() and store it in some variable.
Then compare the stored time to the current time every time a video finishes playing. If more than one hour has elapsed, then end the playback.
You can do something like this
var startTime;
var videoSources =
["http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.html5videoplayer.net/videos/toystory.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"];
var currentIndex =0;
//listener function changes src
function myNewSrc(){
startTime = new Date;
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src=videoSources[currentIndex];
myVideo.load();
}
function myAddListener(){
if ((new Date) - startTime > (60 * 60 * 1000)) {
return;
}
var myVideo=document.getElementsByTagName('video')[0];
currentIndex=(currentIndex+1)%videoSources.length;
myVideo.src=videoSources[currentIndex];
myVideo.addEventListener('ended',myNewSrc,false);
}

Jquery play video or image in div with interval

I have a jQuery array. What I want to do is fetch an image or video and play it until the specified interval and then play next video or image:
Here is my code:
var side_block_src= [{media:'images/172422009.jpg',interval:10},
{media:'images/172422001.jpg',interval:50},
{media:'images/172422009.jpg',interval:4}
];
var sec = 0;
for(var i = 0; i < side_block_src.length; i++) {
console.log('start');
sec = side_block_src[side_block_src].interval*1000;
setTimeout(function(){
$('#setdata>iframe').attr('src',side_block_src[side_block_src].media);
},sec);
}
Why is it not working?
Update
I made it more simple here is the working code
var i = 0;
show_next(i);
function show_next(i){
if(i <= side_block_src.length - i ){
$('#setdata>iframe').attr('src',side_block_src[i+1].media);
setTimeout(function(){
show_next(i + 1)
}, side_block_src[i+1].interval * 1000);
} else {
i=0;
show_next(i);
}
}
You can use
anything slider jquery plugin for this as below i have used
<script type="text/javascript" src="js/ad/jquery.anythingslider.js"></script>
<script type="text/javascript" src="js/ad/jquery.anythingslider.fx.js"></script>
<script type="text/javascript" src="js/ad/jquery.easing.1.2.js"></script>
$('#slider').anythingSlider({
autoPlay: true,
animationTime: 600,
//expand : true,
// Autoplay video in initial panel, if one exists
onInitialized: function(e, slider) {
playvid(slider);
},
// pause video when out of view
onSlideInit: function(e, slider) {
var vid = slider.$lastPage.find('video');
if (vid.length && typeof(vid[0].pause) !== 'undefined') {
vid[0].pause();
}
},
// play video
onSlideComplete: function(slider) {
playvid(slider);
},
// pause slideshow if video is playing
isVideoPlaying: function(slider) {
var vid = slider.$currentPage.find('video');
return (vid.length && typeof(vid[0].pause) !== 'undefined' && !vid[0].paused && !vid[0].ended);
}
});
and here is html code for it
<ul id="slider">
<li class="panel5">
<video class="Cmsvideo" controls autoplay>
<source src="PATH_OF_VIDEO" type="video/EXTENTION_OF_VIDEO" >
Your browser does not support the video tag. But you could include an iframe/embeded video here. </video>
</li>
<li><img src="PATH_OF_IMAGE" alt="" /></li>
</ul>
Here is my solution:
var i = -1;
showNext(i);
function showNext(i) {
if (side_block_src.length - i > 1) {
$('#setdata>iframe').attr('src',side_block_src[i+1].media);
setTimeout(function()
{
showNext(i + 1)
}, side_block_src[i + 1].interval * 1000);
}
}

Preload mp3 file in queue to avoid any delay in playing the next file in queue

I am working on a script where i am playing multiple mp3 and each files is in queue. There is slight delay in playing next .mp3 file as it takes time to buffer/load the file.
How can i buffer the next .mp3 file which is queue so that all file run smoothly without any delay.
getData(1);
function getData(id) {
//Emty div
$("#surah-wrapper").empty();
$.ajaxSetup({
cache: true,
jsonpCallback: 'quranData'
}); // define ajax setup
// Quran Text Type quran-uthmani | quran-simple | quran-simple-clean | quran-wordbyword
$.getJSON("http://api.globalquran.com/surah/" + id + "/quran-uthmani?key=api_key&jsoncallback=?", {
format: "jsonp"
}, function(data) {
if (id > 1) {
$("<span class='qspan qspan-bsm'>").html("بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ").appendTo("#surah-wrapper");
}
$.each(data.quran, function(i, by) {
$.each(by, function(verseNo, line) {
//$("<p>").html('('+ line.surah+':'+line.ayah+') '+line.verse).appendTo("#surah-wrapper");
$("<span class='qspan' id='" + verseNo + "'>").html(line.verse + '<span class="qspan-ayahno">(' + line.surah + ':' + line.ayah + ')</span>').appendTo("#surah-wrapper");
});
});
});
}
//Play Script & highlight script
var audioIndex = 0;
var countSpan = 0;
countSpan = $('#surah-wrapper').children().length;
var surahNo = 1;
var strCat = "http://download.quranicaudio.com/verses/Sudais/mp3/001001.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001002.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001003.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001004.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001005.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001006.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001007.mp3";
setPlayer();
$('.customSurah').change(function() {
$('.play-btn').css('display', 'none');
$aud.pause();
surahNo = $('#surah option:selected').val();
setTimeout(function() {
countSpan = $('#surah-wrapper').children().length;
var i = 0;
strCat = '';
for (i = 0; i <= countSpan; i++) {
if (i == 0) {
strCat = "http://download.quranicaudio.com/verses/Sudais/mp3/001001.mp3,";
i += 1
}
if (i == countSpan) {
if (surahNo == 1) {
} else {
if (i < 10) {
strCat += "http://download.quranicaudio.com/verses/Sudais/mp3/00" + surahNo + "00" + i + ".mp3,";
}
}
} else {
if (i < 10) {
strCat += "http://download.quranicaudio.com/verses/Sudais/mp3/00" + surahNo + "00" + i + ".mp3,";
}
}
}
if (surahNo == 1) {
strCat = null;
strCat = "http://download.quranicaudio.com/verses/Sudais/mp3/001001.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001002.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001003.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001004.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001005.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001006.mp3,http://download.quranicaudio.com/verses/Sudais/mp3/001007.mp3";
}
setPlayer();
$('.play-btn').css('display', 'block');
}, 3000);
});
function setPlayer() {
//reset values
audioIndex = 0;
countSpan = 0;
countSpan = $('#surah-wrapper').children().length;
strCat = strCat.trim();
var audioTracks = strCat;
var audioAddress = audioTracks.split(',');
var playing = false;
$(function() {
$aud = $("#myAudio")[0];
$btn = $(".play-btn");
function setAudio(index) {
$("#surah-wrapper > .qspan").removeClass("qplaying");
$aud.preload = 'auto';
$aud.src = audioAddress[index];
}
setAudio(audioIndex);
$btn.click(function() {
if (playing) {
playing = false;
$aud.pause();
} else
$aud.play();
});
$aud.onended = function() {
if (audioIndex < audioAddress.length - 1) {
audioIndex++;
setAudio(audioIndex);
$aud.play();
} else {
audioIndex = 0;
setAudio(audioIndex);
playing = false;
$btn.text("Play");
}
};
$aud.onpause = function() {
if (!playing) $btn.text("Play");
$(".play-btn").css("background-image", "url(https://cdn0.iconfinder.com/data/icons/cosmo-player/40/button_play_1-64.png)");
};
$aud.onplay = function() {
$btn.text("Pause");
$(".play-btn").css("background-image", "url(https://cdn0.iconfinder.com/data/icons/cosmo-player/40/button_pause_1-64.png)");
playing = true;
$("#surah-wrapper > .qspan:nth-child(" + (audioIndex + 1) + ")").addClass("qplaying");
var wHeight = $(window).height();
var wHalfHeight = wHeight;
var x = $(".qplaying").offset();
var curentSpanPosition = x.top;
wHalfHeight = wHalfHeight / 2;
if (curentSpanPosition > wHalfHeight) {
$('html, body').animate({
scrollTop: curentSpanPosition - 50
}, 1000);
}
};
});
}
.play-btn {
background-image: url("https://cdn0.iconfinder.com/data/icons/cosmo-player/40/button_play_1-64.png");
float: none;
font-size: 0 !important;
height: 50px;
margin: 15px auto;
padding: 5px 10px;
text-align: center;
width: 50px;
}
body{float:right; direction:rtl;}
span{padding:5px 10px; direction:rtl; text-align:right;
margin:5px 1px;
font-size:20px}
.qplaying {
background: #f00 none repeat scroll 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="myAudio" >
<source src="" type="audio/mpeg">
</audio>
<div class="play-btn-wrapper">
<select class="customSurah form-control ddCountry styled-select" id="surah" name="surah" onchange="getData($('#surah option:selected').val())"><option value="1">Al-Faatiha</option><option value="2">Al-Baqara</option><option value="3">Aal-i-Imraan</option><option value="4">An-Nisaa</option><option value="5">Al-Maaida</option><option value="6">Al-An'aam</option><option value="7">Al-A'raaf</option><option value="8">Al-Anfaal</option><option value="9">At-Tawba</option><option value="10">Yunus</option><option value="11">Hud</option><option value="12">Yusuf</option><option value="13">Ar-Ra'd</option><option value="14">Ibrahim</option><option value="15">Al-Hijr</option><option value="16">An-Nahl</option><option value="17">Al-Israa</option><option value="18">Al-Kahf</option><option value="19">Maryam</option><option value="20">Taa-Haa</option><option value="21">Al-Anbiyaa</option><option value="22">Al-Hajj</option><option value="23">Al-Muminoon</option><option value="24">An-Noor</option><option value="25">Al-Furqaan</option><option value="26">Ash-Shu'araa</option><option value="27">An-Naml</option><option value="28">Al-Qasas</option><option value="29">Al-Ankaboot</option><option value="30">Ar-Room</option><option value="31">Luqman</option><option value="32">As-Sajda</option><option value="33">Al-Ahzaab</option><option value="34">Saba</option><option value="35">Faatir</option><option value="36">Yaseen</option><option value="37">As-Saaffaat</option><option value="38">Saad</option><option value="39">Az-Zumar</option><option value="40">Al-Ghaafir</option><option value="41">Fussilat</option><option value="42">Ash-Shura</option><option value="43">Az-Zukhruf</option><option value="44">Ad-Dukhaan</option><option value="45">Al-Jaathiya</option><option value="46">Al-Ahqaf</option><option value="47">Muhammad</option><option value="48">Al-Fath</option><option value="49">Al-Hujuraat</option><option value="50">Qaaf</option><option value="51">Adh-Dhaariyat</option><option value="52">At-Tur</option><option value="53">An-Najm</option><option value="54">Al-Qamar</option><option value="55">Ar-Rahmaan</option><option value="56">Al-Waaqia</option><option value="57">Al-Hadid</option><option value="58">Al-Mujaadila</option><option value="59">Al-Hashr</option><option value="60">Al-Mumtahana</option><option value="61">As-Saff</option><option value="62">Al-Jumu'a</option><option value="63">Al-Munaafiqoon</option><option value="64">At-Taghaabun</option><option value="65">At-Talaaq</option><option value="66">At-Tahrim</option><option value="67">Al-Mulk</option><option value="68">Al-Qalam</option><option value="69">Al-Haaqqa</option><option value="70">Al-Ma'aarij</option><option value="71">Nooh</option><option value="72">Al-Jinn</option><option value="73">Al-Muzzammil</option><option value="74">Al-Muddaththir</option><option value="75">Al-Qiyaama</option><option value="76">Al-Insaan</option><option value="77">Al-Mursalaat</option><option value="78">An-Naba</option><option value="79">An-Naazi'aat</option><option value="80">Abasa</option><option value="81">At-Takwir</option><option value="82">Al-Infitaar</option><option value="83">Al-Mutaffifin</option><option value="84">Al-Inshiqaaq</option><option value="85">Al-Burooj</option><option value="86">At-Taariq</option><option value="87">Al-A'laa</option><option value="88">Al-Ghaashiya</option><option value="89">Al-Fajr</option><option value="90">Al-Balad</option><option value="91">Ash-Shams</option><option value="92">Al-Lail</option><option value="93">Ad-Dhuhaa</option><option value="94">Ash-Sharh</option><option value="95">At-Tin</option><option value="96">Al-Alaq</option><option value="97">Al-Qadr</option><option value="98">Al-Bayyina</option><option value="99">Az-Zalzala</option><option value="100">Al-Aadiyaat</option><option value="101">Al-Qaari'a</option><option value="102">At-Takaathur</option><option value="103">Al-Asr</option><option value="104">Al-Humaza</option><option value="105">Al-Fil</option><option value="106">Quraish</option><option value="107">Al-Maa'un</option><option value="108">Al-Kawthar</option><option value="109">Al-Kaafiroon</option><option value="110">An-Nasr</option><option value="111">Al-Masad</option><option value="112">Al-Ikhlaas</option><option value="113">Al-Falaq</option><option value="114">An-Naas</option></select>
<div class="play-btn"></div>
</div>
<div id="surah-wrapper"></div>
THIS IS THE ACTUAL SCRIPT that i want to implement same: I would appreciate solution in context with script mentioned in the fiddle.
http://codepen.io/anon/pen/pRKreo
Here's you go. The biggest challenge I had was handling the value of this within the handler. Set your <audio> elements to preload="none". My script loads the next song as soon as you play one before it and auto-plays next song once first one finishes.
If you're worried about Global Scope just put it in an IIFE. Enjoy!
var files = document.getElementsByTagName('audio');
var songs = [];
var index = 0;
var Song = function(element) {
this.index = index;
this.playing = function(event) {
try {
files[this.index].preload = "auto";
}
catch (e) {
}
};
this.ended = function(event) {
try {
files[this.index].play();
}
catch (e) {
}
};
element.addEventListener('playing', this.playing.bind(this), false);
element.addEventListener('ended', this.ended.bind(this), false); // Trick
};
for (var len = files.length, i = 0; i < len; ++i) {
index++;
songs.push(new Song(files[i]));
}
ul{
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<meta name="description" content="HTML5 Media Auto Player Skeleton" />
<title>HTML5 Media Auto Player Skeleton</title>
<style>
</style>
</head>
<body>
<main>
<ul>
<li class="album">
<h3 class="album-title">HTML5 Media Player w Auto Next</h3>
</li>
<li>
<audio controls="controls" class="full-width" preload="metadata">
<source src="//rack.international/samples/AttritionDantesKitchenwWHellmixSAMPLE.mp3" type="audio/mpeg">
<source src="//rack.international/samples/AttritionDantesKitchenwWHellmixSAMPLE.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</li>
<li>
<audio controls="controls" class="full-width" preload="metadata">
<source src="//rack.international/samples/AttritionDantesKitchenRascalKlonermxSAMPLE3.mp3" type="audio/mpeg">
<source src="//rack.international/samples/AttritionDantesKitchenRascalKlonermxSAMPLE3.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</li>
<li>
<audio controls="controls" class="full-width" preload="metadata">
<source src="//rack.international/samples/crankRingtone.mp3" type="audio/mpeg">
<source src="//rack.international/samples/crankRingtone.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</li>
</body>
</html>
You can use Promise.all(), Array.prototype.map(), Audio() constructor, canplaythrough event to load all audio first; then use Array.prototype.reduce(), Promise constructor to play audio in sequence at ended event.
var audioAddress = [
"http://download.quranicaudio.com/verses/Sudais/mp3/003001.mp3",
"http://download.quranicaudio.com/verses/Sudais/mp3/003002.mp3",
"http://download.quranicaudio.com/verses/Sudais/mp3/003003.mp3",
"http://download.quranicaudio.com/verses/Sudais/mp3/003004.mp3",
"http://download.quranicaudio.com/verses/Sudais/mp3/003005.mp3",
"http://download.quranicaudio.com/verses/Sudais/mp3/003006.mp3"
];
$("button").click(function() {
Promise.all(audioAddress.map(function(url) {
return new Promise(function(resolve) {
var audio = new Audio(url);
audio.oncanplay = function() {
resolve(audio);
}
})
}))
.then(function(data) {
data.reduce(function(promise, a, index) {
return promise.then(function() {
return new Promise(function(resolve) {
a.onended = resolve;
a.play();
$("p > span").removeClass("playing");
$("p > span:nth-child(" + (index + 1) + ")")
.addClass("playing");
})
})
}, Promise.resolve())
})
});
#myAudio {
display: none;
}
span {
margin: 0px 10px;
}
.playing {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button>Play Audio</button>
<p>
<span>Verse 1</span>
<span>Verse 2</span>
<span>Verse 3</span>
<span>Verse 4</span>
<span>Verse 5</span>
<span>Verse 6</span>
</p>
You can also create a mix of the sequence of audio tracks to play as a single track Is it possible to mix multiple audio files on top of each other preferably with javascript and use AudioContext.linearRampToValueAtTime Web audio api, stop sound gracefully.

How do I pause an HTML video and resume automatically over a loop?

I have a 4 second long video embedded in my HTML page using video tag. I need to pause the video for 2 secs first at 2.99s, 3.44s and then at 4.00s. For that to happen the video needs to resume from previous instance.
But after long hours of effort I haven't been able to find a solution. Thus far I have just been able to get the video paused for >=2.99s but it does not resume even after I had used setInterval function.
Here is the code:
var vTag = document.getElementById('video');
setInterval(function() { pVideo();}, 2000);
function pVideo() {
vTag.ontimeupdate = function(e) {
cTime = vTag.currentTime;
(cTime >= 2.9 || cTime >= 3.44 || cTime >= 4.00) ? vTag.pause(): vTag.play();
};
};
PS: The video is being used as a background video for header section.
Try this.. this is a fully working code
HTML
<video id="video" autoplay muted loop>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
JS
var vTag = document.getElementById('video');
vTag.play();
var wasPausedBefore1 = 0;
var wasPausedBefore2 = 0;
var wasPausedBefore3 = 0;
vTag.ontimeupdate = function(e) {
cTime = vTag.currentTime;
if (cTime < 1) {
wasPausedBefore1 = 0;
wasPausedBefore2 = 0;
wasPausedBefore3 = 0;
} else if (cTime > 2.8 && cTime < 3.1 && wasPausedBefore1 == 0) {
vTag.pause();
wasPausedBefore1 = 1;
setTimeout(function() {
vTag.play();
}, 4000);
} else if(cTime > 3.3 && cTime < 3.6 && wasPausedBefore2 == 0){
vTag.pause();
wasPausedBefore2 = 1;
setTimeout(function() {
vTag.play();
}, 4000);
} else if(cTime > 3.8 && cTime < 4.0 && wasPausedBefore3 == 0){
vTag.pause();
wasPausedBefore3 = 1;
setTimeout(function() {
vTag.play();
}, 4000);
}
};
And here is a working fiddle : https://jsfiddle.net/o9mknsx0/1/
You'll need to update your if statement to track the pause values somehow, otherwise your video will not play because after 2.9 seconds, the if will always return true for all those conditions.
var vTag = document.getElementById('video');
setInterval(pVideo, 2000); //function reference
var nextPause = [2.9, 3.44, 4.00];
var pauseIndex = 0;
function pVideo() {
vTag.ontimeupdate = function(e) {
cTime = vTag.currentTime;
var pauseTime = nextPause[pauseIndex];
if (cTime >= pauseTime) {
vTag.pause();
setTimeout(vTag.play, 2000); //unpause after 2 seconds
if (++index <= nextPause.length) index++
else index = 0;
}
}
};
This is untested and my logic may be flawed, but I feel like the concept is sound.
Put all your pause times into an array, and track the last used index (resetting as well, if need be (looping video)). Then, if the if statement matches, pause the video and run a timeout for 2 seconds to play the video again.
Use setTimeout instead of setInterval.
I'm not sure if you'd be able to catch the times you need using timeupdate since it fires either every 200ms or 250ms but I'd do it like so:
var vTag = document.getElementById('video');
vTag.addEventListener('timeupdate', function() {
var cTime = vTag.currentTime;
if(cTime === 2.99 || cTime === 3.44 || cTime === 4)) {
vTag.pause();
setTimeout(function() {
vTag.play();
}, 2000);
}
});
For it to catch your times like 2.99 and 3.44 then you need to poll for it every 10ms using setInterval.
setInterval(function() {
var cTime = vTag.currentTime;
if(cTime === 2.99 || cTime === 3.44 || cTime === 4) {
vTag.pause();
setTimeout(function() {
vTag.play();
}, 2000);
}
}, 10);

Categories