Stop sound in a react component - javascript

My app is playing some audios depending on various triggers. I want the user to be able to stop the sound when he decides it.
this is what I did, based on this post:
audioPlayer(sound){
const audioGetReady = new Audio("...mp3")
const audioTenSec = new Audio("...mp3");
const audioNext = new AudioAudio("...mp3");
const audioRest = new AudioAudio("...mp3")
const audioCongrats = new AudioAudio("...mp3")
if(sound == 'getReady'){
audioGetReady.play()
}
if(sound == 'tenSeconds'){
audioTenSec.play()
}
if(sound == 'next'){
audioNext.play()
}
if(sound == 'rest'){
audioRest.play()
}
if(sound == 'congrats'){
audioCongrats.play()
}
if(sound == 'stop'){
audioGetReady.pause();
audioGetReady.currentTime = 0;
audioTenSec.pause();
audioTenSec.currentTime = 0;
audioNext.pause();
audioNext.currentTime = 0;
audioRest.pause();
audioRest.currentTime = 0;
audioCongrats.pause();
audioCongrats.currentTime = 0;
}
}
It doesn't work, I also tried to use ".muted = true;" as shown here

I think your code should be like below. In your code, every time you call audioPlayer function, new Audio object is created, which means the audio you start and pause are different.
audioGetReady = new Audio("...mp3");
audioTenSec = new Audio("...mp3");
audioNext = new AudioAudio("...mp3");
audioRest = new AudioAudio("...mp3");
audioCongrats = new AudioAudio("...mp3");
audioPlayer(sound){
if(sound == 'getReady'){
this.audioGetReady.play()
}
if(sound == 'tenSeconds'){
this.audioTenSec.play()
}
if(sound == 'next'){
this.audioNext.play()
}
if(sound == 'rest'){
this.audioRest.play()
}
if(sound == 'congrats'){
this.audioCongrats.play()
}
if(sound == 'stop'){
this.audioGetReady.pause();
this.audioGetReady.currentTime = 0;
this.audioTenSec.pause();
this.audioTenSec.currentTime = 0;
this.audioNext.pause();
this.audioNext.currentTime = 0;
this.audioRest.pause();
this.audioRest.currentTime = 0;
this.audioCongrats.pause();
this.audioCongrats.currentTime = 0;
}
}

Related

Parsing Strings and Integers in JavaScript

I am new to JavaScript and HTML and am hoping someone can notice what I am doing wrong (I'm sure it is probably something small that I am just missing). I have been looking at this for a while, and I cannot seem to figure it out.
The problem is that branch #2 (identified in the comment within the code) is returning NaN for the houseVal which is supposed to return either sf for single-family or tw for townhouse/condo.
I have a JavaScript form I am making. Here it is:
function getPrice() {
var form = document.getElementById("calc");
var out = form.elements["z"];
//get numbers
var sqftVal = parseInt(form.elements["sqft"].value);
var bathsVal = parseInt(form.elements["baths"].value);
var builtVal = parseInt(form.elements["built"].value);
var lotVal = parseInt(form.elements["lot"].value);
for (i = 0; i < document.forms[0].zipcode.length; i++) {
if (document.forms[0].zipcode[i].checked) {
var zipVal = parseInt(document.forms[0].zipcode[i].value);
}
}
for (i = 0; i < document.forms[0].gar.length; i++) {
if (document.forms[0].gar[i].checked) {
var garageVal = parseInt(document.forms[0].gar[i].value);
}
}
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
if (zipVal == "47") {
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 1;
}
else { //townhouse
out.value = houseVal; // <------ PROBLEM: returns NaN <------------
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 3;
}
else { //townhouse
out.value = 4;
}
}
}
else { //zip == 20148
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 5;
}
else { //townhouse
out.value = 6;
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 7;
}
else { //townhouse
out.value = 8;
}
}
}
}
</script>
and here is the Home Type (e.g., Single Family or Townhouse/Condo) part of the form.
...
<fieldset>
<legend>House Type</legend>
<div>
<input type="radio" id="sf" name="housetype" value="sf" />
<label for="sf">Single Family</label>
</div>
<div>
<input type="radio" id="tw" name="housetype" value="tw" />
<label for="tw">Townhouse/Condo</label>
</div>
</fieldset>
...
It looks like in your javascript code you are trying to convert the houseVal to an integer though it's only ever "sf" or "tw"
If you change the following block:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
To:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = document.forms[0].housetype[i].value;
}
}
You should be good
Your value attributes for each radio button are letter based strings. You cannot feasibly use parseInt on letter-based strings .
var houseVal = parseInt(document.forms[0].housetype[i].value);
This is going to cause you issues.

Onclick event in JS shows results for a second before automatically resetting form

This is a simple quiz/questionnaire, that'll display results of the quiz on submission. It shows the results, but only for about half a second before resetting the page. I would also like for the page to show an alert if the user says they're under 18 when the quiz is submitted; it wouldn't keep them from seeing the answers, but just giving them a message.
function checkAge() {
if(age<18) {
alert("Always make sure you have adult supervision while caring for and handling any venomous arachnid.");
} }
function generateAnswers() {
var choice1score = 0;
var choice2score = 0;
var choice3score = 0;
var choice4score = 0;
}
var chosenAnswers = document.getElementsByTagName('result');
for (i=0; i<chosenAnswers.length; i++) {
if (chosenAnswers[i].checked) {
// add 1 to that choice's score
if (chosenAnswers[i].value == 'choice1') {
choice1score = choice1score + 1;
}
if (chosenAnswers[i].value == 'choice2') {
choice2score = choice2score + 1;
}
if (chosenAnswers[i].value == 'choice3') {
choice3score = choice3score + 1;
}
if (chosenAnswers[i].value == 'choice4') {
choice4score = choice4score + 1;
}
}
}
var maxscore = Math.max(choice1score,choice2score,choice3score,choice4score);
var resultBox = document.getElementById('result');
if (choice1score == maxscore) {
resultBox.innerHTML = "Asian Forest Scorpion"
}
if (choice2score == maxscore) {
resultBox.innerHTML = "Deathstalker Scorpion"
}
if (choice3score == maxscore) {
resultBox.innerHTML = "Desert Hairy Scorpion"
}
if (choice4score == maxscore) {
resultBox.innerHTML = "Emperor Scorpion"
}
}
This is where I put the code:
https://codepen.io/cryceks/pen/vjgzOZ
Use:
event.preventDefault();
This prevents the webpage from reloading and therefore clearing form data

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

HTML5 Audio - stop current play when another sound is started

I am using this method to play audio files when you click on an image:
http://jsfiddle.net/v97Kq/3/
function imageSwitch(_imgID, _imgStart, _imgStop, _soundFileMp3, _soundFileOgg) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.song = new Audio();
if (this.song.canPlayType("audio/mpeg"))
this.song.src = _soundFileMp3;
else
this.song.src = _soundFileOgg;
this.song.loop = true;
this.pos = 0;
this.e;
this.change = function () {
if (this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.song.play();
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.song.pause();
}
}
}
It works good! - but how can I get it to stop playing the currently playing sound when another link is clicked and another sound begins?
I found this solution to my issue above, works perfectly.
which I eventually found here:
<script>
var currentPlayer;
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
if(currentPlayer && currentPlayer != thissound) {
currentPlayer.pause();
}
if (thissound.paused)
thissound.play();
else
thissound.pause();
thissound.currentTime = 0;
currentPlayer = thissound;
}
</script>

Javascript not working while inserting image object in html

MAJOR EDIT: Re-Did a lot of things. But similar error.
var white = 1;
var turn = white;
var table = document.getElementById("game");
function createTable(table, white) {
var i,j,tr;
for(i=0;i<8;i++)
{
tr = document.createElement('tr');
for(j=0;j<8;j++)
tr.appendChild(document.createElement('td')).id = String.fromCharCode( (white == 1 ? j : 8-j) +97)+(white == 1 ? 8-i : i+1);
table.appendChild(tr);
}
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
table.rows[i].cells[j].setAttribute("class","cell");
}
}
}
function onImageLoad(t) {
console.log(t);
}
function createImageArray() {
var w,c,p;
var image = new Array(2);
for(w=0;w<2;w++)
{
image[w] = new Array(2);
for(c=0;c<2;c++)
{
image[w][c] = new Array(6);
for(p=0;p<6;p++)
{
image[w][c][p] = new Array(2);
}
}
}
return image;
}
function createBlankimageArray() {
var blank = new Array(2);
return blank;
}
function bufferImages(image,blank) {
var w, c, p, s, word;
for(w=0;w<2;w++)
{
for(c=0;c<2;c++)
{
for(p=0;p<6;p++)
{
for(s=0;s<2;s++)
{
word = w.toString() + c.toString() + (p+1).toString() + s.toString() + ".png";
//console.log(word);
image[w][c][p][s] = new Image();
image[w][c][p][s].onload = onImageLoad(word);
image[w][c][p][s].src='final images/'+ word;
}
}
}
}
for(i=0;i<2;i++)
{
blank[i] = new Image();
word = i.toString() + '.png';
blank[i].onload = onImageLoad(word);
blank[i].src= 'final images/'+ word;
}
}
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
function drawState(table,state,image,blank) {
var y,x;
//var table = document.getElementById("game");
var w,c,p;
for(y=0;y<8;y++)
{
for(x=0;x<8;x++)
{
c = state[y][x][0];
w = state[y][x][1];
p = state[y][x][2];
if(p!=7)
{
table.rows[y].cells[x].appendChild(image[w][c][p][0]);
}
else
{
table.rows[y].cells[x].appendChild(blank[c]);
}
}
}
}
var state = intializeState();
var image = createImageArray();
var blank = createBlankimageArray();
createTable(table, white);
bufferImages(image,blank);
intializeState(state);
drawState(table,state,image,blank);
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Anti Chess</title>
<link rel="stylesheet" type="text/css" href="screen2.css">
</head>
<body>
<h1 id="game_title">Anti Chess by theManikJindal</h1>
Visit Blog!
<br />
<br />
<table id="game"></table>
<script src="req_logic.js"></script>
</body>
</html>
The above script is required to create a chess board in the initial position.
The problem that I am encountering is in the drawState function.
Console: (has printed out all the image names after loading them) After that:
Uncaught TypeError: Cannot read property '1' of undefined req_logic.js:154
Which is the line: table.rows[y].cells[x].appendChild(image[w][c][p][0]);
so where have I gone wrong.
EDIT: jsFiddle.net link : http://jsfiddle.net/8H3Ha/1/
Change the definition ot initializeState() to:
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
Then call it as:
state = initializeState();
The problem is that the parameter variable named state was shadowing the global variable with the same name inside initializeState.
I also suggest that the elements of the state array should be objects, not arrays. Arrays should be used when the elements are uniform, but each of these sub-elements have different purposes: [0] is the cell color, [1] is the piece, and [2] is the piece color.

Categories