JavaScript and HTML: audio that overlap eachother - javascript

I'm working for studies purposes on a web site that can help people with visual impairment. The site has to play audio files thanks to keyboard's buttons. My problem is: when I play an audio (for example audio1) and then I play another one (for example audio2), the two audio overlap eachother. My idea is to stop an audio using another button, for example X. So, if audio1 is playing and I press X, then audio1 should stop. I'll add my code here.
Thanks.
// HTML:
<audio src="audio/homepage_benvenuto.mp3" autoplay>
<audio src="audio/homepage_0.mp3" id="audio0">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_1.mp3" id="audio1">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_2.mp3" id="audio2">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_3.mp3" id="audio3">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_4.mp3" id="audio4">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_5.mp3" id="audio5">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_6.mp3" id="audio6">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_7.mp3" id="audio7">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_8.mp3" id="audio8">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_9.mp3" id="audio9">
<p>Your browser does not support the audio element.</p>
</audio>
<audio src="audio/homepage_I.mp3" id="audioI">
<p>Your browser does not support the audio element.</p>
</audio>
// JavaScript:
var source = "audio/homepage_benvenuto.mp3"
var audio = document.createElement("audio");
audio.autoplay = true;
audio.load()
audio.addEventListener("load", function()
{
audio.play();
}, true);
audio.src = source;
function checkKeyPressed(e)
{
var player;
if (e.keyCode == "48") // 48 = 0
{
document.getElementById('audio0').play()
player = document.getElementById('audio0');
}
if (e.keyCode == "49") // 49 = 1
{
document.getElementById('audio1').play()
player = document.getElementById('audio1');
}
if (e.keyCode == "50") // 50 = 2
{
document.getElementById('audio2').play()
player = document.getElementById('audio2');
}
if (e.keyCode == "51") // 51 = 3
{
document.getElementById('audio3').play();
player = document.getElementById('audio3');
}
if (e.keyCode == "52") // 52 = 4
{
document.getElementById('audio4').play();
player = document.getElementById('audio4');
}
if (e.keyCode == "53") // 53 = 5
{
document.getElementById('audio5').play();
player = document.getElementById('audio5');
}
if (e.keyCode == "54") // 54 = 6
{
document.getElementById('audio6').play();
player = document.getElementById('audio6');
}
if (e.keyCode == "55") // 55 = 7
{
document.getElementById('audio7').play();
player = document.getElementById('audio7');
}
if (e.keyCode == "56") // 56 = 8
{
document.getElementById('audio8').play();
player = document.getElementById('audio8');
}
if (e.keyCode == "57") // 57 = 9
{
document.getElementById('audio9').play();
player = document.getElementById('audio9');
}
// Here I tried to create a script to stop the audio, but it doesn't work
if (e.keyCode == "88") // 88 = X: interrompe audio in corso
{
player.pause();
player.currentTime = 0;
}

Alright so I have taken a look into your code, but the problem is that you store your 'player' variable inside of your checkKeyPressed(e) method. So each time you call the checkKeyPressed method your variable player will be reset, because at the beginning of the method you redeclare it with 'var player;'.
To fix this make sure the player variable is outside of your method like this:
var player = null;
function checkKeyPressed(e)
{
if (e.keyCode == "48") // 48 = 0
{
document.getElementById('audio0').play()
player = document.getElementById('audio0');
}
if (e.keyCode == "49") // 49 = 1
{
document.getElementById('audio1').play()
player = document.getElementById('audio1');
}
if (e.keyCode == "50") // 50 = 2
{
document.getElementById('audio2').play()
player = document.getElementById('audio2');
}
if (e.keyCode == "51") // 51 = 3
{
document.getElementById('audio3').play();
player = document.getElementById('audio3');
}
if (e.keyCode == "52") // 52 = 4
{
document.getElementById('audio4').play();
player = document.getElementById('audio4');
}
if (e.keyCode == "53") // 53 = 5
{
document.getElementById('audio5').play();
player = document.getElementById('audio5');
}
if (e.keyCode == "54") // 54 = 6
{
document.getElementById('audio6').play();
player = document.getElementById('audio6');
}
if (e.keyCode == "55") // 55 = 7
{
document.getElementById('audio7').play();
player = document.getElementById('audio7');
}
if (e.keyCode == "56") // 56 = 8
{
document.getElementById('audio8').play();
player = document.getElementById('audio8');
}
// Here I tried to create a script to stop the audio, but it doesn't work
if (e.keyCode == "88") // 88 = X: interrompe audio in corso
{
player.pause();
player.currentTime = 0;
}
}
Little side note: I see you are using e.keyCode == "88" to pause your music. This means you have to use the combination Shift + x to pause the music instead of only pressing x on your keyboard.

Related

html video key control and formatting

I have spent over 5 hours each day for the last 3 days trying to get this to work. I have done research into this topic and nothing I have found on stack overflow, youtube, etc has helped me understand this any more. To give you idea of the purpose of this is to set up a local website (non-online, just a file) and present it as a school project, so it only needs to work in chrome. The idea was to have two titles with 4 images below each,
title
img img img img
title
img img img img
now, I am trying to figure out how to trigger a hidden video to go full screen whenever a button is pressed (each video will have a key labeled beside it) (each image has a different video) and disappear when it is over. The code I attached shows how far I have managed to get trying to get it to work. (I have minimal experience with html and even smaller with css and java, have only ever coded games in c# so I don't understand more complicated aspects).
<html><head>
<title>Full Screen Test</title>
<style type="text/css">
/* make the video stretch to fill the screen in WebKit */
:-webkit-full-screen #myvideo {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<style>
video::-webkit-media-controls {
display:none !important;
}
</style>
<p><strong>Press enter to go fullscreen</strong></p>
<video src="http://videos-cdn.mozilla.net/serv/webmademovies/Moz_Doc_0329_GetInvolved_ST.webm" width="800" id="myvideo">
<script>
var videoElement = document.getElementById("myvideo");
function toggleFullScreen() {
if (!document.mozFullScreen && !document.webkitFullScreen) {
if (videoElement.mozRequestFullScreen) {
videoElement.mozRequestFullScreen();
} else {
videoElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else {
document.webkitCancelFullScreen();
}
}
}
document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
toggleFullScreen();
}
}, false);
</script>
</video>
</body></html>
I think this can help.
You can add the video and try to use fullscreen api, if does not works you use css to simulate fullscreen.
Also use onended to exit fullscreen and hide the player.
Buttons are keypad 0 to 7 [key code 96 to 103]
With the keycode on valid range it gets the correct video index from the array and plays it.
document.addEventListener("keydown", function(e) {
if (e.keyCode >= 96 && e.keyCode <= 103 ) { // Keypad 0 to 7
stopPlaying();
setTimeout(()=> playVideo(e.keyCode-96), 500);
}
}, false);
Hope it helps.
videos = [
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
"https://www.w3schools.com/html/mov_bbb.mp4",
];
removeVideo = function() {
video = document.getElementById("video");
video.remove();
}
playVideo = function (index) {
wrapper = document.getElementById("wrapper");
wrapper.innerHTML = '<video autoplay onended="removeVideo()" id="video" width="320" height="240" controls> <source src="' + videos[index]+'" type="video/mp4"> </video>';
var elem = document.getElementById("video");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
}
function isFullScreen() {
return (document.fullscreenElement && document.fullscreenElement !== null) ||
(document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
(document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
(document.msFullscreenElement && document.msFullscreenElement !== null);
}
function closeFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { /* Firefox */
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { /* IE/Edge */
document.msExitFullscreen();
}
}
function stopPlaying() {
video = document.getElementById("video");
if(isFullScreen()) {
closeFullscreen();
}
if(video) {
video.remove();
}
}
document.addEventListener("keyup", function(e) {
if(e.keyCode == 27 || e.keyCode == 69) { //Esc or e
stopPlaying();
}
}, false);
document.addEventListener("keydown", function(e) {
if (e.keyCode >= 96 && e.keyCode <= 103 ) { // Keypad 0 to 7
stopPlaying();
setTimeout(()=> playVideo(e.keyCode-96), 500);
}
}, false);
#video {
position: fixed;
top: 0;
height: 100vh;
width: 100vw;
}
video::-webkit-media-controls {
display:none !important;
}
<h6> Videos 1 </h6>
<img onclick="playVideo(0)" src="https://via.placeholder.com/50">0
<img onclick="playVideo(1)" src="https://via.placeholder.com/50">1
<img onclick="playVideo(2)" src="https://via.placeholder.com/50">2
<img onclick="playVideo(3)" src="https://via.placeholder.com/50">3
<h6> Videos 2 </h6>
<img onclick="playVideo(4)" src="https://via.placeholder.com/50">4
<img onclick="playVideo(5)" src="https://via.placeholder.com/50">5
<img onclick="playVideo(6)" src="https://via.placeholder.com/50">6
<img onclick="playVideo(7)" src="https://via.placeholder.com/50">7
<div id="wrapper">
<h6> Exit video </h6>
<div>
You can type 'e' to exit the video.
</div>
<div id="wrapper">
</div>

Javascript music player acting weird

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)

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.

Touch control for html5 game

I've been working on a simple html5 canvas game, and I'm trying to add touch controls for devices as well as keyboard input for desktops etc.
The keyboard controls are perfect: space bar is tapped to jump, and held for a longer jump.
I've added event listeners for touch control, which emulate the single tap of the spacebar, but I can't figure out how to recreate holding the space bar for longer jumps with the touch control. My keyboard code looks like this:
// jump if not currently jumping or falling
if (KEY_STATUS.space && player.dy === 0 && !player.isJumping) {
player.isJumping = true;
assetLoader.sounds.jump.play();
player.dy = player.jumpDy;
jumpCounter = 12;
}
// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
player.dy = player.jumpDy;
assetLoader.sounds.jump.play();
}
jumpCounter = Math.max(jumpCounter-1, 0);
this.advance();
And that gets tracked with this code:
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for (var code in KEY_CODES) {
if (KEY_CODES.hasOwnProperty(code)) {
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
My new event listeners for touch screen devices looks like this:
document.addEventListener("touchstart", touchHandler);
document.addEventListener("touchhold", touchHandler);
document.addEventListener("touchend", touchHandler);
And then I have this function, which is more or less identical to the function for keyboard input, only 'e.touches' is referenced, rather than 'KEY_STATUS':
function touchHandler(e) {
if(e.touches && player.dy === 0 && !player.isJumping) {
player.isJumping = true;
assetLoader.sounds.jump.play();
player.dy = player.jumpDy;
jumpCounter = 12;
e.preventDefault();
}
}
That function enables the little jump. If I include this 'if' statement, it enables multiple jumps:
if (e.touches && jumpCounter) {
player.dy = player.jumpDy;
assetLoader.sounds.jump.play();
}
...rather than enabling the player to perform the longer jump. Essentially, the player could tap to fly throughout the game, which I don't want! Is there a way to specify within the 'touchHandler()' function which kind of jump is being made ie. is the screen being tapped or held? Or would I need to write a separate function for that?
Thanks in advance.

Play pause html5

I'm trying to get create a button to pause and play a video and change the innerHTML when clicked. This is what I've tried and I cant understand why it's not working. Can anyone help please:
function play() {
var video = document.getElementById("video1");
video.play();
}
var playButton = document.getElementById("play-pause");
playButton.addEventListener("click", function () {
if (video.paused === true) {
// Play the video
video.play();
// Update the button text to 'Pause'
playButton.innerHTML = "Pause";
} else {
// Pause the video
video.pause();
// Update the button text to 'Play'
playButton.innerHTML = "Play";
}
});
var video = document.getElementById("video1");
var playButton = document.getElementById("play-pause");
playButton.addEventListener("click", function () {
if (video.paused === true) {
video.play();
playButton.innerHTML = "Pause";
} else {
video.pause();
playButton.innerHTML = "Play";
}
});

Categories