It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.
But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.
You can use jquery to solve as I am already using it.
Thank you in advance.
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
I have edited my answer.
The button to start the timer will allow the sound to be played on safari mobile
The timer doesn't re-declare variables and functions like it did before
You could make it cleaner with less global variables but I don't know how the rest of your code would be affected by this so I didn't change it.
<button onclick=start()>start</button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script> <audio id = "songOne" src = "http://www.sousound.com/music/healing/healing_01.mp3" preload = "auto" > </audio>
<script>
// declaring variables
var betNo = 0 ;
var myAudio = document . getElementById ( 'songOne' );
var isPlaying =false;
var togglePlay=function(){
if (isPlaying) {
myAudio . pause (); }
else {
myAudio . play (); } };
myAudio . onplaying = function () { isPlaying = true ;};
myAudio . onpause = function () { isPlaying = false ;};
var start=function(){
// setTimer with only the necessary code inside so variables are not being declared more than once
boxTimer = setInterval ( function (){ if (( betNo == 0 )||( betNo == 10 )){
togglePlay (betNo); }
console . log ( betNo );
betNo ++; if ( betNo >= 20 ){
clearInterval ( boxTimer ); } }, 1000 ); }
</script>
The solution is much simpler (cause was just a silly mistake). Thanks #Rory McCrossan for pointing that out in the comments.
I just took the var isPlaying = false; out of the setInterval function, otherwise it was being set to false even if the song was playing.
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var isPlaying = false;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
Related
Modular refactoring of javascript is in progress. When executing the codes below in the game class start method, an error like this.initTimer is not a function is output. Not only initTimer but also the code below shows an error like is not a function. How can I solve this?
game.js
'use strict';
import * as sound from './sound.js';
import Field from './field.js';
export default class Game{
constructor(gameDuration){
this.gameDuration = gameDuration;
this.gameTimer = document.querySelector('.game__timer');
this.gameField = new Field();
this.gameField.setClickListener(this.onFieldClick);
this.startBtn = document.querySelector('.game__startBtn');
this.startBtn.addEventListener('click', this.start);
this.started = false;
this.timer = undefined;
this.level = 0;
}
onFieldClick = (stage, win) => {
if(!this.started){
return;
}
if(this.level == 0){
if(stage == 'first' && win == 'win'){
this.finish('win');
}else if(stage == 'first' && win == 'lose'){
this.finish('lose');
}
}
if(this.level == 1){
if(stage == 'second' && win == 'win'){
this.finish('win');
}else if(stage == 'second' && win == 'lose'){
this.finish('lose');
}
}
if(this.level == 2){
if(stage == 'third' && win == 'win'){
this.finish('finish');
}else if(stage == 'third' && win == 'lose'){
this.finish('lose');
}
}
}
onItemClick(button) {
if(button == 'next'){
++this.level;
}
if(button == 'finish'){
this.level = 0;
}
start();
}
setGameStopListener(onGameStop){
this.onGameStop = onGameStop;
}
start() {
this.started = true;
this.initTimer();
this.gameField.hideStartContent;
this.setBackgroundImg();
this.showTimer();
sound.playBackground();
this.startTimer();
}
finish(win){
this.started = false;
this.stopTimer();
sound.stopBackground();
if(win == 'win' || win == 'finish'){
sound.playWin();
}
if(win == 'lose') {
sound.playAlert();
}
this.onGameStop && this.onGameStop(win);
}
initTimer(){
this.timer = undefined;
}
setBackgroundImg(){
let imgPath = `url(img/game__field/stage${this.level}.jpg)`;
this.gameField.setBackgroundImage(imgPath);
}
showTimer() {
this.gameTimer.style.visibility = 'visible';
}
startTimer() {
let remainingTimeSec = this.gameDuration;
this.updateTimerText(remainingTimeSec);
this.timer = setInterval(() => {
if(remainingTimeSec <= 0) {
clearInterval(timer);
sound.stopBackground();
this.finish('lose');
return;
}
this.updateTimerText(--remainingTimeSec);
}, 1000);
}
updateTimerText(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
this.gameTimer.innerHTML = `${minutes}:${seconds}`;
}
stopTimer() {
clearInterval(this.timer);
}
}
OutPut
game.js:60 Uncaught TypeError: this.initTimer is not a function
at HTMLImageElement.start (game.js:60)
Expected
Sequencing of code inside start
I believe a problem is in event 'click' handler. Without binding, 'this' is prebound to clicked element, in your case to some img inside button.
this.startBtn.addEventListener('click', this.start.bind(this));
I've been having this problem where audio wouldn't play. I am trying to get a random sound to play but nothing happens when I click on the image (which has an onclick="playRandomSound()"). This is my code.
var sound1 = new Audio("InDeed.wav");
var sound2 = new Audio("Indeed2.wav");
var sound3 = new Audio("Yeeees.wav");
var sound4 = new Audio("girl_shut_up.wav");
var sound5 = new Audio("imhmmm.wav");
var randomizer;
function playRandomSound(){
randomizer = Math.floor(Math.random()*5);
if (randomizer === 0){
sound1.play();
} else if (randomizer == 1){
sound2.play();
} else if (randomizer == 2){
sound3.play();
} else if (randomizer == 3){
sound4.play();
} else if (randomizer == 4){
sound5.play();
}
}
body {
background: white;
}
#rokas {
height: 100vh;
}
<HTML>
<HEAD>
</HEAD>
<BODY>
<img src="https://i.imgur.com/4lO3dpT.jpg" id="rokas" onclick="playRandomSound()">
</BODY>
</HTML>
Please try to update your code like this:
html:
<audio style="display: none;" id="sound"></audio>
js:
function playRandomSound () {
var sound = document.getElementById('sound');
randomizer = Math.floor(Math.random()*5);
if (randomizer === 0){
sound.src = sound1;
} else if (randomizer == 1){
sound.src = sound2;
} else if (randomizer == 2){
sound.src = sound3;
} else if (randomizer == 3){
sound.src = sound4;
} else if (randomizer == 4){
sound.src = sound5;
}
sound.load();
sound.play();
}
Hope it helps.
Add the tag...
<audio id="audioPlaceHolder" src="InDeed.wav" autostart="false" ></audio>
You can dynamically change the src from your JavaScript.
For playing it...
var sound = document.getElementById('audioPlaceHolder');
sound.play();
enjoy!
This is my function
<script>
function animation(times,time,element,patch,forever,restart, frame = 0) {
if(restart ==1){
frame = 0;
$(element).show();
}
this.interval = setInterval(function(){
frame++;
$(element).attr('src',patch+''+frame+'.png');
if(frame == times){
if(forever == 0){
$(element).hide();
clearInterval(this.interval);
} else {
frame = 0;
}
}
},time);
}
</script>
It will be OK if I only use it once. But not OK if i use it much time. Help me.
Currently, I am using an archaic method of setting a variable true at the start of the animation and false after the animation has played (see below.) I also think something might be wrong with how I process animations in the interval because when I add an animation to the array of animations to be processed, it isn't processed. Here's my code:
var animationDone = true;
function g_e(e){
return document.getElementById(e);
};
class Main{
constructor(){
this.animations = [];
this.tasks = [];
}
start_animating(){
var x = setInterval(function (){
if (animationDone == true){
try{
alert(this.animations[0]);
this.aminations[0].func(this.animations[0].args);
this.animations.shift();
}
catch(e){
}
}
},1);
}
add_animation(f, a){
this.animations.push({func:f, args:a});
alert("animation added");
}
start_working(){
var x = setInterval(function (){
try{
this.tasks[0].func(this.tasks[0].args);
this.tasks.shift();
}
catch(e){
}
},1);
}
animation_blink(){
var blink = 0;
window.setInterval(function blinking(){
if (blink == 0){
document.getElementById("blinker").innerHTML = ">";
blink= 1;
}
else if(blink == 1){
document.getElementById("blinker").innerHTML=" ";
blink = 0;
}
}, 1000);
}
animation_fade(object){
var fade = 0;
var fadeOut = 0;
animationDone = false;
var interval = setInterval(function startFade(){
g_e(object.element).style.opacity = fade;
if(fade>1 && fadeOut == 0){
fadeOut = 1;
}
else if(fade < 0){
clearInterval(interval);
}
else if(fadeOut == 0){
fade = fade + 0.2;
}
else if(fadeOut == 1){
fade = fade - 0.2;
}
}, 500);
animationDone = true;
}
plbl(object){
animationDone = false;
var p = plbl.intervals;
if (!p)
plbl.intervals = p = {};
if (p[object.destination])
clear();
function clear() {
clearInterval(p[object.destination]);
delete p[object.destination];
}
var i = 0;
var elem = document.getElementById(object.destination);
p[object.destination] = setInterval(function(){
checkChar = object.message.charAt(i);
if(checkChar =="|"){
elem.innerHTML += "<br>";
}
else{
elem.innerHTML += object.message.charAt(i);
}
i++;
if (i > message.length){
animationDone = true;
clear();
}
}, object.speed);
}
command(input){
alert(input);
if(input == "y"){
g_e("start").style.display = "none";
g_e("startUp").style.display = "block";
this.add_animation("test", "test");
}
}
get_input(){
var x = g_e("input").value;
g_e("input").value = "";
return x;
}
key_checker(event){
var key = event.keyCode;
if (key == 13){
this.command(this.get_input());
return false;
}
}
start(){
this.start_working();
this.start_animating();
this.animation_blink();
}
}
alert("compiled");
main = new Main();
main.start();
I was wondering if there is a way to set the setTimeout function to different timeout on the fly.
So, for example I check something every 1 second, but if I don't get an expected result in like 10 seconds I want to "reconfigure" this setTimeout to wait 3 seconds instead of 1.
Here is my code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9)
waitInterval = 3000;
}
$("#tst").html(waitInterval);
},
waitInterval
);
If you want to check it out here is the mentioned code on jsfiddle: http://jsfiddle.net/Hitman666/Vyczj/2/
You have to stop the interval and restart it. See this fork of your jsfiddle.
EDIT: I've copied your code here in case something happens with your jsfiddle code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 5){
clearInterval(waitForNewRace);
waitInterval += 1000;
if (waitInterval > 10000)
waitInterval = 10000;
waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
var waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
I think this will do what you want:
var br = 0;
var waitForNewRace = setInterval(function(){
checkForNewRace();
if(++br == 9){
clearInterval(waitForNewRace);
setInterval(checkForNewRace, 3000);
}
}, 1000);
function checkForNewRace(){
if($("#data").html() == "1"){
$("#res").html("got it!");
clearInterval(waitForNewRace);
}else
$("#counter").html(br);
$("#tst").html(waitInterval);
}
You could use clearInterval:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
function checkForNewRace(){
console.log(waitForNewRace);
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9){
waitInterval = 3000;
clearInterval(waitForNewRace);
br = 0;
waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
fiddle: http://jsfiddle.net/Vyczj/5/
An alternative, just need to add two lines to your own code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9){
clearInterval(waitForNewRace);
waitInterval = 3000;
waitForNewRace=setInterval(checkForNewRace,waitInterval);
}
}
$("#tst").html(waitInterval);
},
waitInterval
);