control video playlist with global variables - javascript

I have a video playlist that plays videos one after a time.
I need the playlist to continue until it reaches a video with the name loop, and loop the video until one of the global variables lvl1_win or lvl2_loose (from a different script) turn 1.
Depending on the result, play a different playlist, playlist_lvl2 or playlist_lvl1_gameover
This is the Playlist I am currently using. It simply loops the videos one after a time:
var activeloop;
var myvid = document.getElementById('intro_lvl1');
myvid.addEventListener('ended', function (e)
{
var activesource = document.querySelector("#intro_lvl1 source.active");
var nextsource = document.querySelector("#intro_lvl1 source.active +
source") ||
document.querySelector("#intro_lvl1 source:first-child");
//for the video with the name "loop" in it.
var loopsource = document.querySelector("#intro_lvl1 source.loop");
activesource.className = "";
nextsource.className = "active";
myvid.src = nextsource.src;
myvid.play();
});
Could anybody give me a few suggestions on how to implement this?

You can use RegExp.prototype.test() to check if the .src contains "loop", set .loop to true
if (/loop/.test(nextsource.src)) {
// perform logic here
if (myvid.loop != true) {
myvid.loop = true
};
if (lvl1_win == 1 || lvl2_loose == 1) {
// do other stuff
}
}

Thank you for your answer!
I got it to work with the following:
var lvl1_win;
var lvl1_loose;
var myvid = document.getElementById('intro_lvl1');
myvid.addEventListener('ended', function (e) {
var activesource = document.querySelector("#intro_lvl1 source.active");
var nextsource = document.querySelector("#intro_lvl1 source.active +
source") || document.querySelector("#intro_lvl1 source:first-child");
if (/loop/.test(nextsource.src)) {
if (myvid.loop != true) {
myvid.loop = true;
};
if (lvl1_win == 1) {
alert("Won level 1");
}
if (lvl1_loose == 1) {
alert("Gameover level 1");
}
} else {
activesource.className = "";
nextsource.className = "active";
myvid.src = nextsource.src;
myvid.play();
}
});
However, I cannot add the specific video for winning or loosing in the same source, otherwise it would mess up the playlist.
Or is it possible to play the next video with the class loose if lost vise versa?
What I mean:
if (lvl1_loose == 1) {
play next video with class gameover
then play pause video on last frame (ending the cycle)
}

Related

Browser video flickers when switching clip [HTML, JS]

I want to have video clips that seamlessly transition from one to another(with idle animations). For starters, I wanted to use the normal browser player and just switch sources when one clip ends like this:
var videos = [
"video/1.webm",
"video/2.webm",
"video/3.webm",
"video/4.webm",
];
let i = 0;
const videoCount = videos.length;
const element = document.getElementById("video");
element.addEventListener('ended', myHandler, false);
function myHandler() {
i++;
if (i == videoCount) {
i = 0;
}
element.setAttribute("src", videos[i]);
element.autoplay = true;
// element.preload = true;
// element.muted = true;
element.load();
}
The problem is that there is a stutter/flicker or delay before a new clip starts playing(in chrome and firefox). The clips I have don't contain any black or empty frames(clips I have loop fine).
As far as I can tell it shows a blank screen for a frame or two.
Is there any way to preload the clips so they switch instantaneously?
The comments from Will and VC.One were leading me onto the right path. I created 2 video elements and instead of pushing and pulling the z-index I pushed it off screen with:
.hidden {
position: absolute;
left: -100vw;
}
I ended up using this:
var videos = [
"video/v1.webm",
"video/v2.webm",
"video/v3.webm",
// ...
];
var i = 0;
const videoCount = videos.length;
const v1 = document.getElementById("video");
const v2 = document.getElementById("video2");
v1.muted = true;
v2.muted = true;
v1.setAttribute("src", videos[i]);
v1.load();
v1.play();
i++;
v2.setAttribute("src", videos[i]);
v2.load();
v1.addEventListener('ended', vHandler, false);
v2.addEventListener('ended', vHandler, false);
function vHandler() {
if((i+1) == videoCount)
i = 0;
if(i % 2 == 0) {
i++;
v2.setAttribute("src", videos[i]);
v2.load();
v1.classList.remove("hidden");
v2.classList.add('hidden');
v1.play();
} else {
i++;
v1.setAttribute("src", videos[i]);
v1.load();
v2.classList.remove("hidden");
v1.classList.add('hidden');
v2.play();
}
}

Audio on JavsScript when a certain condition is met

I am making a blackjacks game right now and I am having trouble on getting audio in the code, I want it to play audio when a certain condition is met, I want it to pick up an audio file from a local file, and I also want it to autoplay, how can I achieve this? Thanks.
Here is my javascript code:
//adding the cards together, with parameter passing
function cardNumber(one, two) {
var cardTotal = one + two;
alert(`Your card numbers are ${one} and ${two}!`);
return cardTotal;
}
var cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random() * cardRange.length)];
//calling the cardNumber function (parameter passing shown)
var cardSum = cardNumber(cardOne, cardTwo);
//adding the cards together if the user wants an extra card, with parameter passing
function moreCards(nextCard, total) {
alert(`Your extra card is ${nextCard}!`);
var cardTotal = nextCard + total;
return cardTotal;
}
function inputValidation() {
var i;
for (i = 0; i < 3;) {
//Asks the user if they want another card, they can do this up to three times, depending on their choice and card sum.
var input = prompt(`Which makes your card total ${cardSum}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null) {
//takes you back to pontoonhome.html
window.location.replace("pontoonhome.html").src = "homepage";
i += 3;
}
//Random number doesn't change
else if (input === "1") {
i++;
var extraCard = cardRange[Math.floor(Math.random() * cardRange.length)];
//calling the moreCards function
cardSum = moreCards(extraCard, cardSum);
}
else if (input === "0") {
//If the user declines to another card
i += 3;
}
else {
//If the user puts in an invalid input
alert("Wrong input, enter 1 or 0 on your keyboard!");
}
if (cardSum >= 22) {
//If the user gets above 22 (bust)
i += 3;
}
}
}
function pontoonDecision() {
var comScore = 18;
if (cardSum >= 22) {
alert("BUST!");
document.write(`You got ${cardSum}, which is above 21, that means you got a bust! Therefore, you lose!`);
document.getElementById("loss").src = "images/dislike-157252_640.png";
}
else if (cardSum > comScore && cardSum < 22) {
document.write(`You got ${cardSum}, and the AI player got ${comScore}, which means you win! <br>`);
document.getElementById("victory").src = "images/hand-157251_640.png";
//where I want the audio to play.
let audio = document.getElementById("winner").src = "audio/winner.wav";
audio.autoplay();
//not sure how to do it right
}
else if (cardSum === comScore) {
document.write(`You got ${cardSum}, and the AI player got ${comScore}. Which means it is a tie!`);
document.getElementById("draw").src = "images/questions-3409194_640.png"
}
else {
document.write(`You got ${cardSum}, and the AI player got ${comScore}. You got a value lower than the computer's score, meaning you lose!`);
document.getElementById("loss").src = "images/dislike-157252_640.png";
}
}
inputValidation();
pontoonDecision();
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<link rel = "stylesheet" href = "css/styles.css">
<body>
<div class ="title">
<h1>Pontoon</h1>
</div>
<div class ="hyperlinks">
Home
Rules
Start
Contact Us
</div>
<div class="header">
<h2>Game</h2>
</div>
<img id = "victory"></img>
<img id = "loss"></img>
<img id = "draw"></img>
<audio controls autoplay>
<audio id = "winner"></audio>
<!--The audio I want to play^^^-->
</audio>
<a href id = "homepage"></a>
<br>
<script src = "js/pontoonGame3.js">
</script>
<div class = "wrapper">
Exit
Play Again
</div>
</body>
</head>
</html>
let audio = document.getElementById("winner").src = "audio/winner.wav";
You're assigning audio to the contents of src, which is "audio/winner.wav".
Make this two separate statements.
let audio = document.getElementById("winner");
audio.src = "audio/winner.wav";
autoplay is a property of an Audio object, not a function. So calling audio.autoplay() is invalid. You should call play() instead.
let audio = document.getElementById("winner");
audio.src = "audio/winner.wav";
audio.play();
First of all, create a folder audio in the same place as your code (recommended), then include all of the audios you need here
In your HTML, using <audio> tag for each of the audio file, make sure to give them unique IDs to query later:
<audio src="link-to-your-audio.mp3" id="your-audio"></audio>
In your script, just like any other elements, query all the audio tags
const yourAudio = document.getElementById('your-audio');
To play the audio, use .play() or .pause() to stop it, like so:
yourAudio.play();
yourAudio.pause();

How to pause previous audio function?

When I press the button, I want to play a song, when I press the second song a second time, and when the third one, the cycle repeats again, but the first song is shorter than the second one, and if you click many times, the long song plays simultaneously with its other copy. Is it possible to stop the previous music and move on to another?
Html:
< a id="Play">test< / a>
Script:
window.onload=function(){
let number = 0;
var t;
document.getElementById('Play').addEventListener('click',function(){
let audio = new Audio();
if ( number == 0 ) {
audio.src = '/assets/sound/test.mp3';
number = 1;
}
else
if ( number == 1 ) {
audio.src = '/assets/sound/curious&loony.mp3';
number = 0;
}
audio.autoplay = true;
});
}
sound.pause();
sound.currentTime = 0;
Use this for pause audio
Found a way.
How to:
<script>
var i = 1, player = new Audio();
player.src = "/assets/sound/sound1.mp3";
document.querySelector('#play-button').addEventListener('click', function(e) {
e.preventDefault();
if (i === 1) {
player.src = "/assets/sound/sound1.mp3";
i = 0;
} else if (i === 0) {
player.src = "/assets/sound/sound2.mp3";
i = 1;
}
player.play();
});
</script>
Play me harder

can't choose seek time of a video from a scroll bar

I want to use a video tag and control it with javascript,
but it doesn't work as I want.
function vidplay(evt) {
if (video.src == "") { // inital source load
getVideo();
}
button = evt.target; // get the button id to swap the text based on the state
if (video.paused) { // play the file, and display pause symbol
video.play();
button.textContent = "||";
} else { // pause the file, and display play symbol
video.pause();
button.textContent = ">";
}
}
// load video file from input field
function getVideo() {
var d = document.getElementById('a4').innerHTML; // video file name
// var fileURL = document.getElementById("videoFile").value; // get input field
var fileURL = d; // get input field
if (fileURL != "") {
video.src = fileURL;
video.load(); // if HTML source element is used
document.getElementById("play").click(); // start play
} else {
errMessage("Enter a valid video URL"); // fail silently
}
}
var d in function getVideo() is like "http://192.168.44.112/~/~.mp4"
This video was uploaded on mongoDB and I want to use it.
The video works well but the seek bar doesn't work at all,
it only seeks to time 0.
document.getElementById("rew").addEventListener("click", function() {
setTime(-10);
}, false);
document.getElementById("fwd").addEventListener("click", function() {
setTime(10);
}, false);
function setTime(tValue) {
// if no video is loaded, this throws an exception
try {
if (tValue == 0) {
video.currentTime = tValue;
} else {
video.currentTime += tValue;
}
} catch (err) {
// errMessage(err) // show exception
errMessage("Video content might not be loaded");
}
}
And when i use setTime() function, it goes to seek time 0, while I want to seek at the time corresponding to where I click .
How can I do it ?
I made this quick example that you can test & study, then afterwards you can just apply a similar logic to your above shown code. Hope it helps your problem.
<video id="myVid" width="640" height="480" controls>
<source src="yourVideoFile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
tValue = 0; //start at zero
myVid.addEventListener('seeking', function(e){ tValue = myVid.currentTime })
function setTime_FWD()
{
try
{
if (tValue >= myVid.duration) { tValue = myVid.duration; }
else { tValue += 10; myVid.currentTime = tValue; }
}
catch (err) { errMessage("Video content might not be loaded"); }
}
function setTime_RWD()
{
try
{
tValue -= 10;
if (tValue <= 0) { myVid.currentTime = tValue = 0; }
else { myVid.currentTime = tValue; }
}
catch (err) { errMessage("Video content might not be loaded"); }
}
</script>
<br><br>
<button onclick="setTime_RWD()"> << </button>
<button onclick="setTime_FWD()"> >> </button>

video play loop play another ja

I need a video to play and loop seamlessly a defined number of times, then skip to a next video and loop seamlessly a defined number of times, and so forth until the playlist ends.
In one page, a user defines videos to be played, as well as how many times it will "loop" (or iterate). These are stored using session variables as:
$_SESSION["Exer[" .$x. "]"]
$_SESSION["Reps[" . $x. "]"].
I'm ignoring this aspect (the php stuff) currently
I have code that independently works, one that loops and one that plays playlists, but I can't seem to manage the merger of them together to achieve functionality. The code is as followed:
HTML
<video width="320" height="240" id="myVideo" autoplay="autoplay">
</video>
JavaScript
For looping:
<script>
var iterations = 1;
document.getElementById('iteration').innerText = iterations;
document.getElementById('myVideo').src = "Video/01.mp4";
myVideo.addEventListener('ended', function () {
if (iterations < 3) {
this.currentTime = 0;
this.play();
iterations ++;
document.getElementById('iteration').innerText = iterations;
}
}, true);
</script>
For playlist:
<script>
var videoSource = new Array();
videoSource[0] = "Video/01.mp4";
videoSource[1] = "Video/02.mp4";
videoSource[2] = "Video/03.mp4";
videoSource[3] = "Video/04.mp4";
var i = 0; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}
</script>
Any help is appreciated.
Please check this, this java script code will replay a video for mentioned number of times and then plays next video if exists in playlist:
var eachVdoLoop = 2;
var currentVdoLoop=0;
var videoSource = new Array();
videoSource[0] = "http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_1mb.mp4";
videoSource[1] = "https://www.w3schools.com/html/mov_bbb.mp4";
var videoCount = videoSource.length;
var vdoIndex=0;
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
nextVideo();
function myHandler() {
currentVdoLoop++;
if(currentVdoLoop < eachVdoLoop)
{
document.getElementById("myVideo").play();
}
else
{
vdoIndex++;
currentVdoLoop=0;
nextVideo();
}
}
function nextVideo() {
if(vdoIndex == videoSource.length)
{
alert("Playlist ended!!!")
return;
}
document.getElementById("myVideo").setAttribute("src", videoSource[vdoIndex]);
document.getElementById("myVideo").play();
}
An working jsfiddle (fiddle updated)

Categories