Javascript music player acting weird - javascript

I have multiple issues with the following code.
<audio id="player" autoplay loop >
<source id="mp3Source" src="" type="audio/mp3">
</audio>
<script>
var vid = document.getElementById('player');
vid.volume = 0.3;
function loadSong(songNo) {
var mp3Source = document.getElementById('mp3Source');
mp3Source.src = 'songs/' + songNo + '.mp3';
};
$(window).keydown(function(evt) {
if (evt.which == 107) {
if (vid.volume < 1) {
vid.volume = Math.max( Math.ceil((vid.volume + 0.1) * 10) / 10)
}
}
if (evt.which == 109) {
if (vid.volume > 0) {
vid.volume = Math.max( Math.ceil((vid.volume - 0.1) * 10) / 10)
}
}
if (evt.which == 32) {
vid.volume = 0
}
if (evt.which == 97) {
loadSong(1)
}
if (evt.which == 98) {
loadSong(2)
}
});
</script>
Now, first issue being when you play with the keys (+ / -), when you press + a few times and then spam - the vid.volume will get stuck at same float number and won't go below that number but it will still go above. Second issue is that I can rarely hear music play in browser, it seems like it's random? I am not sure if there's something wrong with my code or it's the way thing has to work.
To sum up issues, when playing with keys (-) key will get stuck and volume won't decrease and when opening .html file the music does not play in browser, only plays randomly (if you refresh or relaunch file)

Related

Pure JavaScript Slideshow Play/Pause with Spacebar

I'm trying to make a JavaScript slideshow (here's the fiddle) with automatically-playing audio for each slide with the functionality to allow right arrow (for next slide), left arrow (for previous slide), or space bar to play from the current slide to the last slide, with space bar also being used to pause the slideshow (and then again to resume, etc.).
The only problem I am experiencing is with getting the space bar to pause the slideshow. For debugging, I'm logging to the console when it is suppose to pause, and it seems to be executing this functionality the number of times as the slide number, albeit without actually pausing the slideshow--e.g. if I push space bar when on slide 2, it executes twice, but if I push space bar yet again when it reaches slide 4, it executes 6 times (2+4), etc.
I have tried the following code most recently to no avail:
(function loop(){
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
if (slidenumber >= slidelength || breakout == "1") return;
setTimeout(function(){
if (breakout == "1") return;
console.log("slide #: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}, 1000);
})();
I've also tried this failing code:
(function loop() {
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
setTimeout(function() {
if (slidenumber >= slidelength || breakout == "1") {console.log("breakout on slide #" + slidenumber + "!"); return;}
else {
console.log("slide ##: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}
},1000);
})();
...and this failing code:
for (a = slidenumber; a < slidelength; a++) {
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused!");}})
if (breakout == "1"){break;}
(function(ind) {
setTimeout(function(){
showDivs(slidenumber += 1);
}, 2 * 1000 * ind); // Change slide every 2 seconds
})(a);
}
And even this failing code:
var func = function(slidenumber){
return function(){
if (slidenumber >= slidelength) return;
console.log("turn no. " + slidenumber);
showDivs(slidenumber += 1);
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused!");}})
if(breakout == "1") {
console.log('slideshow paused');
} else {
setTimeout(func(++slidenumber), 2000);
}
}
}
setTimeout(func(0), 2000);
What can I do to get this to work? My entire code is:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slideshow</title>
</head>
<body style="text-align: center;">
<div class="slide-content">
<img style="height:80vh;" onclick="play(1)" src="https://images.unsplash.com/photo-1541963463532-d68292c34b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Mnx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-1" src="https://soundbible.com/grab.php?id=2218&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(2)" src="https://images.unsplash.com/photo-1546521343-4eb2c01aa44b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8M3x8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-2" src="http://soundbible.com/grab.php?id=2212&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(3)" src="https://images.unsplash.com/photo-1543002588-bfa74002ed7e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MXx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-3" src="http://soundbible.com/grab.php?id=2210&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(4)" src="https://images.unsplash.com/photo-1507842217343-583bb7270b66?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Nnx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-4" src="http://soundbible.com/grab.php?id=2204&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(5)" src="https://images.unsplash.com/photo-1532012197267-da84d127e765?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8NHx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-5" src="http://soundbible.com/grab.php?id=2184&type=mp3"></audio>
</div>
<div onclick="plusDivs(-1)">Previous</div>
<div onclick="plusDivs(1)">Next</div>
<script>
var slidelength = document.getElementsByClassName("slide-content").length;
function play(nr) {
var audio = document.getElementById("audio-"+nr); audio.play();
}
var slidenumber = 1;
showDivs(slidenumber);
function plusDivs(n) {
showDivs(slidenumber += n);
}
function showDivs(n) {
var i;
var slide = document.getElementsByClassName("slide-content");
if (n > slidelength) {slidenumber = n-1} // Do not loop
if (n < 1) {slidenumber = n+1} // If left is pushed on first slide, stay on first slide
for (i = 0; i < slidelength; i++) {
slide[i].style.display = "none";
}
slide[slidenumber-1].style.display = "block";
console.log("# of slides: " + slidelength);
console.log("slide #: " + slidenumber);
play(slidenumber);
}
window.addEventListener('keydown', function(pronounce) {
if (pronounce.keyCode == 39) {showDivs(slidenumber += 1);} // Right Arrow
if (pronounce.keyCode == 37) {showDivs(slidenumber -= 1);} // Left Arrow
// Space bar, when pushed, should loop through automatically until last slide. if space bar is pushed again pause. if pushed yet again continue. etc.
if (pronounce.keyCode == 32) { // Space Bar
// Working, but not the pause
(function loop(){
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
if (slidenumber >= slidelength || breakout == "1") return;
setTimeout(function(){
if (breakout == "1") return;
console.log("slide #: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}, 1000);
})();
}
})
</script>
</body>
</html>

jQuery html5 audio move step back or jump forward shortcut

I am using the following code to play/pause html5 audio player using the button \:
$(document).keypress(function(e) {
var video = document.getElementById("myAudio");
// \
if ((e.which == 92) || (e.keyCode==92)) {
if (video.paused)
video.play();
else
video.pause();
}
});
I want to add keyboard shortcuts to step back 5 seconds (using ctrl+left arrow) or jump forward 5 seconds (using ctrl+right arrow) from the current location.
I have a script, but I am not sure how to edit it to do that:
let toggleChecked, toggleEnabled, observer, dirVideo, settings = {
skip: 5,
};
skipLeft: function(v,key,ctrl){
v.currentTime -= settings.skip;
},
skipRight: function(v,key,ctrl){
v.currentTime += settings.skip;
},
Here is a jsfiddle with the first script: https://jsfiddle.net/12jpk4L0/
Your js need to look like this
var video = document.getElementById("myAudio");
$(document).keypress(function(e) {
// \
if ((e.which == 92) || (e.keyCode==92)) {
if (video.paused)
video.play();
else
video.pause();
}
});
$(document).keydown(function(e) {
if ((e.which == 37) || (e.keyCode == 37)) {
if (video.currentTime - 5 > 0) {
video.currentTime -= 5;
}
}
if ((e.which == 39) || (e.keyCode == 39)) {
if (video.currentTime + 5 < video.duration) {
video.currentTime += 5;
}
}
});
Arrow keys are triggered by keydown not keypress function.

Play sound on different prayer Times in ionic 2

I want to play sound in my ionic2 App on different prayer Times saved in db
e.g this is my GUI
here i am playing music in opening a div like:
in Html
<div item-right *ngIf="playAudio">
<audio controls autoplay="true">
<source [src]="this.audio">
</audio>
</div>
and in my ts file:
setInterval(() => {
var d = new Date();
var hours = d.getHours();
var min = d.getMinutes();
var minutes;
if (min < 10) {
minutes = "0" + min;
this.time = hours + ":" + minutes;
} else {
this.time = hours + ":" + min;
}
if (this.showPrayerTimes == true) {
this.checkprayerTime();
}
}, 60000)
checkprayerTime() {
if (this.time == this.prayerTime.FajarTime) {
this.playAudio= true;
}
else if (this.time == this.prayerTime.DhuhrTime) {
this.playAudio= true;
}
else if (this.time == this.prayerTime.AsrTime) {
this.playAudio= true;
}
else if (this.time == this.prayerTime.MaghribTime) {
this.playAudio= true;
}
else if (this.time == this.prayerTime.IshaTime) {
this.playAudio= true;
}
else if (this.time == this.prayerTime.JumuahTime) {
this.playAudio= true;
}
else {
console.log("time do not match");
}
}
it is working in this current page(only when we are on this page) but what if i want to check the prayer time in my app no matter on what page i am it checks and plays audio .
Thanks in advance
you can create separate Component for checking and playing and add that Component in the top of the App.
(kind of global header/footer component)
In my App component.ts I used set interval function and it runs in complete app and work as a background process in my app and plays sound regardless of at what page I am.

Game loop for card game, winner starts, 1 user controlled player

I'm looking to program a card game where there is one user-controlled player, playing against 3 a.i opponents. It is a game of Euchre, you can find a similar example here:
https://cardgames.io/euchre/
In this card game, the player that wins the round, starts the next round. The game automatically continues
I am having trouble trying to find a way to handle the user event. The click event needs to action the user-controlled player playing a card, and then the other players in clockwise order.
The problem is that if the user-controlled player does not win the hand, the game must continue playing until the user-controlled player needs to play again, at which point they will be required to fire another click event.
What would be the best way to solve this problem? I have a JSFiddle which I think does what I want, but it's really not ideal:
https://jsfiddle.net/GerardSimpson/m736364e/18/
var player1 = {};
player1.hasPlayed = false;
var roundStarter = 0;
var i = 0;
var currentTurn = (i + roundStarter) % 4;
while(player1.hasPlayed === false) {
console.log("player[",currentTurn,"]", "plays a card");
i++;
currentTurn = (i + roundStarter) % 4;
if(i === 4) {
roundStarter = 2;
console.log("Round Over, player "+ roundStarter +" wins");
i = 0;
currentTurn = (i + roundStarter) % 4;
}
if(currentTurn === 0) {
console.log("player[ 0 ]s turn, exit loop and wait for new click event");
player1.hasPlayed = true;
}
}
I have managed to find a solution to my problem, the trick was to put the turn functionality into a function that modifies variables in the parent scope that keep a record of the game turn. I think I may need to add closures to this if I don't want to polute the global scope. I will update later, here is my code and fiddle:
var player1 = {};
player1.hasPlayed = false;
var roundStarter = 0;
var i = 0;
var currentTurn = (i + roundStarter) % 4;
$('.click-me').on('click', function(){
while(1) {
console.log("player[",currentTurn,"]", "plays a card");
i++;
currentTurn = (i + roundStarter) % 4;
if(i === 4) {
roundStarter = 3;
console.log("Round Over, player "+ roundStarter +" wins");
i = 0;
currentTurn = (i + roundStarter) % 4;
}
if(currentTurn === 0) {
console.log("player[ 0 ]s turn, exit loop and wait for new click event");
break;
}
}
});
http://jsfiddle.net/GerardSimpson/m736364e/23/

Embedding audio

I have created a Pomodoro clock(timer). I want to play a sound after each session or break ends.
function countDownTimer() {
timer = setInterval(function() {
if (!pause) {
if (sec == 0) {
if (minutes !== 0)
minutes--;
if (minutes == 0 && hours !== 0) {
display(hours, minutes, sec);
hours--;
minutes = 59;
}
display(hours, minutes, sec = 59);
} else {
sec--;
display(hours, minutes, sec);
}
}
}, 1000);
}
function display(hr, min, sec) {
checkIfOver(hr,min,sec);
if (hr < 10)
hr = "0" + hr;
if (min < 10)
min = "0" + min;
if (sec < 10)
sec = "0" + sec;
document.getElementById("clock").innerHTML = hr + ":" + min + ":" + sec;
}
function checkIfOver(hr,min,sec){
if ((hr == 0 && min == 0 & sec == 0) && session == true) {
session = false;
breaks = true;
if (confirm("Session is over. Start Break??"))
setTime();
else {
clearInterval(timer);
document.getElementById("start").disabled = false;
}
} else if ((hr == 0 && min == 0 & sec == 0) && breaks == true) {
session = true;
breaks = false;
if (confirm("Break is over. Start Session??"))
setTime();
else {
clearInterval(timer);
document.getElementById("start").disabled = false;
}
}
}
I have tried embedding an audio src through html and playing it via js. Also I have tried using an audio object. Is there any other way to do it??
Full Code here:http://codepen.io/jpninanjohn/pen/WwBWpO?editors=1010
Convert to mp3 format and use the HTML5 audio element:
<audio src="success.mp3">
Your browser does not support the audio element.
</audio>
Another solution is to create the Audio object directly without any html elements:
var audio = new Audio('success.mp3');
audio.play();

Categories