Audio on JavsScript when a certain condition is met - javascript

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();

Related

Subtract an image that is representing a life in a game

Im try to code a mini game.
The game has two boxes you can click on. The boxes are assigned a random number between 1 and 2.
When the game starts, you have 5 lives. These lives are represented as 5 pictures of a small human.
When the player gets 3,5 and 7 correct points you get a extra life. Which i have achieved.
Now im trying to subtract a life everytime the player clicks on the wrong box.
function setRandomNumber() {
randomNumber = Math.floor(Math.random() * 2 + 1);
if (randomNumber === 1) {
numberOfRightAnswersSpan.innerHTML = `${++correctNumber}`;
outputDiv.innerHTML = `Det er riktig svar.`;
if (correctNumber === 3 || correctNumber === 5 || correctNumber === 7) {
numberOfLivesDiv.innerHTML += `<img src="images/person1.jpg"/>`
}
} else {
numberOfWrongAnswersSpan.innerHTML = `${++wrongNumber}`;
outputDiv.innerHTML = `Det er feil svar.`;
}
}
I made a few changes to your code, but tried to keep it fairly similar to your original. I changed your template literals to strings. I changed your .innerHTML modifications to .innerText modifications. I refactored some whitespace to make your if statement more readable. Instead of adding the img element by appending the html string, I used the .appendChild method and createElement method to make the img elements. I also added a class to the element to make it easier to grab later.
function setRandomNumber() {
randomNumber = Math.floor(Math.random() * 2 + 1);
if (randomNumber === 1) {
numberOfRightAnswersSpan.innerText = ++correctNumber;
outputDiv.innerText = "Det er riktig svar.";
if (
correctNumber === 3 ||
correctNumber === 5 ||
correctNumber === 7
) {
const newLife = document.createElement("img");
newLife.src = "images/person1.jpg";
newLife.classList.add("life");
numberOfLivesDiv.appendChild(newLife);
}
} else {
numberOfWrongAnswersSpan.innerText = ++wrongNumber;
outputDiv.innerText = "Det er feil svar.";
const aLife = document.querySelector(".life");
aLife.remove();
}
}
It is important to note at this point there is not logic to check for how many life exists, or what to do when lives run out. Eventually you may hit an error because there is not element with a class of life.
I would re-render the lives every time the number of lives changes.
let number_of_lives = 5;
const lives_container = document.getElementById("user-lives");
function draw_lives(){
lives_container.innerHTML = "";
for(let i = 0; i < number_of_lives; i++){
const img = document.createElement("img");
img.setAttribute("alt", "life.png");
const new_life = img;
lives_container.appendChild(new_life);
};
if(number_of_lives <= 0) lives_container.innerText = number_of_lives;
};
function remove_life() {
number_of_lives--;
draw_lives();
};
function add_life() {
number_of_lives++;
draw_lives();
};
draw_lives();
#user-lives > * {
margin: 10px;
background: #7f7;
}
<div id="user-lives"></div>
<button onclick="add_life();">Add life</button>
<button onclick="remove_life();">Remove life</button>

Play a random video on button click

I should start by saying I'm not good with JS and I'm still trying to learn it.
I have 10 mp4s and I need to play one at random on a button click. I'm having trouble making it happen and I've searched around for a solution but to no avail.
Here's what I have so far:
HTML
<div class="videoHolder">
<video id="video" autoplay muted>
Your browser does not support the video tag.
</video>
</div>
<button type="button" name="button">Push to Play</button>
JS
var videos = [
"mp4s/video1.mp4",
"mp4s/video2.mp4",
"mp4s/video3.mp4",
"mp4s/video4.mp4",
"mp4s/video5.mp4",
"mp4s/video6.mp4",
"mp4s/video7.mp4",
"mp4s/video8.mp4",
"mp4s/video9.mp4",
"mp4s/video10.mp4",
];
var videoId = 0;
var elemVideo = document.getElementById('video');
var elemSource = document.createElement('source');
elemVideo.appendChild(elemSource);
elemVideo.addEventListener('ended', play_next, false);
function play_next() {
if (videoId == 10) {
elemVideo.stop();
} else {
video.pause();
elemSource.setAttribute('src', videos[videoId]);
videoId++;
elemVideo.load();
elemVideo.play();
}
}
play_next();
</script>
This unfortunately doesn't do what I need. This code will play all 10 videos one after the other on page load, then stop. I need it to only play one of the random 10 videos when someone pushes the "Push to Play" button. And I need it to keep going after 10.
Like I said I'm not good with JS at all and I was able to find this code from browsing around and modifying it a bit.
This should work for you.
<div class="videoHolder">
<video id="video" autoplay muted src="">
</video>
</div>
<button id='playRandom' type="button" name="button">Push to Play</button>
This is a really basic implementation of what you want
var videos = [
"mp4s/video1.mp4",
"mp4s/video2.mp4",
"mp4s/video3.mp4",
"mp4s/video4.mp4",
"mp4s/video5.mp4",
"mp4s/video6.mp4",
"mp4s/video7.mp4",
"mp4s/video8.mp4",
"mp4s/video9.mp4",
"mp4s/video10.mp4"
];
var videoId = getRandomInt(0, 9);
var elemVideo = document.getElementById('video');
elemVideo.setAttribute('src', '/' + videos[videoId]);
var btn = document.getElementById('playRandom');
btn.addEventListener('click', function (e) {
var nextId = getRandomInt(0, 9);
if (nextId != videoId) {
playNext(nextId);
} else {
while (nextId == videoId) {
nextId = getRandomInt(0, 9);
}
playNext(nextId);
}
});
/* gets random whole number between 0 and 9 */
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function playNext(id) {
elemVideo.setAttribute('src', '/' + videos[id]);
elemVideo.play();
}
This is a more robust implementation that includes a history of previously played videos so you don't play the same videos over again.
var videos = [
"mp4s/video1.mp4",
"mp4s/video2.mp4",
"mp4s/video3.mp4",
"mp4s/video4.mp4",
"mp4s/video5.mp4",
"mp4s/video6.mp4",
"mp4s/video7.mp4",
"mp4s/video8.mp4",
"mp4s/video9.mp4",
"mp4s/video10.mp4"
];
var playedVideos = [];
var videoId = getRandomInt(0, 9);
var elemVideo = document.getElementById('video');
elemVideo.setAttribute('src', '/' + videos[videoId]);
var btn = document.getElementById('playRandom');
btn.addEventListener('click', playRandom);
function playRandom(e) {
var nextId = getRandomInt(0, 9);
if (nextId != videoId) {
if (!playNext(nextId)) {
playRandom(e);
}
} else {
while (nextId == videoId) {
nextId = getRandomInt(0, 9);
}
if (!playNext(nextId)) {
playRandom(e);
}
}
}
/* gets random whole number between 0 and 9 */
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function playNext(id) {
// checks if the video has already been played
for (var src in playedVideos) {
if (src == videos[id]) {
return false;
}
}
elemVideo.setAttribute('src', '/' + videos[id]);
elemVideo.play();
// adds src to arr of played videos
playedVideos.push(videos[id]);
/*
* Everything from here on is optional depending on whether you want to
* - iterate over the arr of videos and play each videos at least once before starting over or
* - you want to stop playing videos after playing each at least once
*/
// empties the played videos arr and allows you to start playing a new set of random videos
if (playedVideos.length() == 10) {
playedVideos = [];
// if you'd like to stop playing videos altogether at this, point delete the previous statement and display a prompt saying the playlist is over
// or if you'd like to reset the playlist, then remove the event listener ('playRandom') and display a reset button that starts everything over from the beginning.
}
return true;
}

minor problem with control structure not executing code the way I want it to

Making a game us JS which selects a winner based on who gets to a certain number the first. however when I implement an if statement it breaks my game as this IF statement is to merely stop the game as soon as a winner has been selected.
when I remove the if statement the code works and selects a winner however, you can still keep clicking on the dice roll button and this is not what I want to happen here. Thank you in advance!
var scores, roundScore, currentPlayer, playTime;
game();
document.querySelector(".btn-roll").addEventListener("click", function() {
if (playTime) {
// 1. random number generator
var dice = Math.floor(Math.random() * 6) + 1;
console.log(dice);
// 2. display the result
var diceDom = document.querySelector(".dice");
diceDom.style.display = "block";
diceDom.src = "/images/dice-" + dice + ".png";
// 3. update the round score if the rolled number was not a 1
if (dice !== 1) {
// i. add score
roundScore += dice;
document.querySelector(
"#current-" + currentPlayer
).textContent = roundScore;
} else {
// ii. next player
nextPlayer();
}
}
});
document.querySelector(".btn-hold").addEventListener("click", function() {
if (playTime) {
// 4. add current players score to global score
scores[currentPlayer] += roundScore;
// i. update UI
document.querySelector("#score-" + currentPlayer).textContent =
scores[currentPlayer];
// ii. check who one the game
if (scores[currentPlayer] >= 10) {
document.querySelector("#name-" + currentPlayer).textContent =
"You are the winner!";
document.querySelector(".dice").style.display = "none";
document
.querySelector(".player-" + currentPlayer + "-panel")
.classList.add("winner");
document
.querySelector(".player-" + currentPlayer + "-panel")
.classList.remove(".active");
playTime = false;
} else {
// iii. next player
nextPlayer();
}
}
});
function nextPlayer() {
currentPlayer === 0 ? (currentPlayer = 1) : (currentPlayer = 0);
roundScore = 0;
//iii. reset scores to 0
document.getElementById("current-0").textContent = "0";
document.getElementById("current-1").textContent = "0";
//iiii. toggle active class for selected player
document.querySelector(".player-0-panel").classList.toggle("active");
document.querySelector(".player-1-panel").classList.toggle("active");
//iiiii. remove dice image when new player is appointed
document.querySelector(".dice").style.display = "none";
}
document.querySelector(".btn-new").addEventListener("click", game);
function game() {
scores = [0, 0];
currentPlayer = 0;
roundScore = 0;
// hide dice on intital page load
document.querySelector(".dice").style.display = "none";
// reset scores to 0
document.getElementById("score-0").textContent = "0";
document.getElementById("score-1").textContent = "0";
document.getElementById("current-0").textContent = "0";
document.getElementById("current-1").textContent = "0";
document.getElementById("name-0").textContent = "Player 1";
document.getElementById("name-1").textContent = "Player 2";
// reset colour of player panels
document.querySelector(".player-0-panel").classList.remove("winner");
document.querySelector(".player-1-panel").classList.remove("winner");
document.querySelector(".player-0-panel").classList.remove("active");
document.querySelector(".player-1-panel").classList.remove("active");
// re adding the active class
document.querySelector(".player-1-panel").classList.add("active");
}
I am expecting the If statement (playTime) which is located just under the queryselector '.btn-roll' to stop the game as soon as the winner is announced. but instead it is just not allowing this part of the code to run

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

control video playlist with global variables

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)
}

Categories