Stopping an audio track on a mouse click event - javascript

I'm learning some beginners front end development. I've created a very simple website which utilizes the Lightbox kit. I have worked out how to start an audio track when someone clicks a thumbnail but need some pointers as to how to stop it, or for a more robust solution, play the appropriate track if someone clicks the 'next' arrow. Here is my code so far:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/lightbox.min.css">
<script src="js/lightbox-plus-jquery.min.js"></script>
<meta charset="utf-8">
<title>verenti ltd</title>
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<meta name="author" content="SitePoint">
</head>
<body bgcolor="#F7FBED ">
<div class="gallery">
<a href="images/drake_big.jpg" data-lightbox="mygallery" data-title="nick drake"
onclick=PlaySound("music/drake.mp3")><img src="images/drake_small.jpg"></a>
<a href="images/prine_big.jpg" data-lightbox="mygallery" data-title="john prine"
onclick=PlaySound("music/prine.mp3")> <img src="images/prine_small.jpg"></a>
<a href="images/westerberg_big.jpeg" data-lightbox="mygallery" data-title="paul westerberg"
onclick=PlaySound("music/westerberg.mp3")> <img src="images/westerberg_small.jpg"></a>
<a href="images/townes_big.png" data-lightbox="mygallery" data-title="townes van zandt"
onclick=PlaySound("music/townes.mp3")> <img src="images/townes_small.jpg"></a>
<script>
function PlaySound(path) {
//this function will work like a toggler for sound track playing
var sound = document.getElementById(path);
if(sound && sound.currentTime > 0){ //check whether it is already playing
sound.pause();// stop the sound
sound.currentTime = 0 //
}else if(sound){
//this block to play paused sound track
sound.play();
}else{
//this block to play new sound track
sound= document.createElement('audio');
sound.setAttribute('src', path);
sound.setAttribute('id', path);
sound.play();
}
}
</script>
</div>
</body>
</html>
I think I could be making better use of the tag?

A simple solution will be:
<script>
function PlaySound(path) {
//this function will work like a toggler for sound track playing
var sound = document.getElementById(path);
if(sound && sound.currentTime > 0){ //check whether it is already playing
sound.pause();// stop the sound
sound.currentTime = 0 //
}else if(sound){
//this block to play paused sound track
sound.play();
}else{
//this block to play new sound track
sound= document.createElement('audio');
sound.setAttribute('src', path);
sound.setAttribute('id', path);
sound.play();
}
}
</script>

Related

How to still play the video after pausing once but after control is being enabled, the addeventlistener is not working at all?

I am a beginner in JavaScript, I want to play and pause the video whenever the user clicks the video element, but when in my code once user clicks again the video element the video gets paused and control gets enabled but when again user clicks the paused video after the controls being enabled the addEventListener() is not working at all it seems, can anyone please tell why this is happening, I saw that after I remove line videoelement.controls = true; then all works fine, but I want to know why this is happening and is there any way that with controls enabled it works fine enough
let videoelement = document.querySelector('.videos')
videoelement.addEventListener('click', function (e) {
console.log(videoelement.paused)
if (videoelement.paused) {
console.log("pause hai ")
videoelement.play();
videoelement.controls = null;
videoelement.firstChild.nodeValue = 'Play';
} else {
console.log("play ho gya")
videoelement.pause();
videoelement.controls = true;
videoelement.firstChild.nodeValue = 'Pause';
}
e.preventDefault();
})
body
{
background-color: blueviolet
}
.videos
{
width: 50%;
margin:10% 20%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Player</title>
<link rel="stylesheet" href="videplayercss.css">
</head>
<body>
<div class="videoplayer">
<video src="anyvideo.mp4" autoplay class="videos"> </video>
</div>
<script src="videoplayerjs.js"></script>
</body>
</html>

How do you make a sound play when a hyperlinked image/text is clicked (still taking you to the hyperlinked webpage)

I'm doing an SDD assessment and I'm making a website kind of game. It will be a choose your own adventure game and I'm trying to incorporate JavaScript. I have 3 buttons that will take the user to different pages and I would like each of the buttons to make a sound when they're clicked. The buttons are text with a sword image above them, so I'd like a sword sound to play. However, I'm not experienced with JavaScript. I found some code for it at https://www.daniweb.com/programming/web-development/threads/286059/play-sound-when-a-link-is-clicked
but it means nothing to me cause I don't know how to use it. Would someone be able to explain to me what it means and how to adapt it to my HTML and CSS?
Here's my HTML code
<html>
<head>
<meta charset="UTF-8">
<title>SDD Minor Project Code</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/js" href="script.js">
</head>
<body>
<div class="home_sword">
<a href="https://trinket.io/html/c11627b947?outputOnly=true&runMode=autorun">
<img id="home_button_img" src="button_underline_sword_left.png">
<h2><i>Home</i></h2>
</a>
</a>
</div>
<div>
<img class="left_shield" src="shield_title_bookend.png">
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png">
</div>
<img class="scroll" src="story_scroll.png">
<div class="narrative">
<p>Hello, World!</p>
</div>
</body>
</html>
Here's an exemple of what i made on one of my projects when i was learning JavaScript
<script>
function soundAlarm() {
let amount = 3; // count of sound you want here is set on 3 but you can change it as much you want
let audio = new Audio("Timer_Sound_Effect.mp3"); //here variable for the src of the sound
function playSound() { // function that plays the sound
audio.pause();
audio.currentTime = 0;
audio.play();
}
for (let i = 0; i < amount; i++) { // loop to play as many times you asked in "let amount "
setTimeout(playSound, 1200 * i); // 1200 = 1200 mseconds between each times the sound plays.
}
}
</script>
In html just put as attribute to play it:
<html>
<head>
</head>
<body>
<div>
<img class="left_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
</div>
</body>
</html>
Here's your code with the modifications :) :
<html>
<head>
<meta charset="UTF-8">
<title>SDD Minor Project Code</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/js" href="script.js">
</head>
<body>
<div class="home_sword">
<a href="https://trinket.io/html/c11627b947?outputOnly=true&runMode=autorun">
<img id="home_button_img" src="button_underline_sword_left.png">
<h2><i>Home</i></h2>
</a>
</a>
</div>
</a>
</a>
</div>
<div>
<img class="left_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
<h1 class="story_title"><i>Viking Attack</i></h1>
<img class="right_shield" src="shield_title_bookend.png" onclick="soundAlarm()"> <!-- function called on the click to play the sound-->
</div>
<img class="scroll" src="story_scroll.png">
<div class="narrative">
<p>Hello, World!</p>
</div>
</body>
<script>
function soundAlarm() {
let amount = 3; // count of sound you want here is set on 3 but you can change it as much you want
let audio = new Audio("Timer_Sound_Effect.mp3"); //here variable for the src of the sound, change it by the path of your file, or directly by your file name if in same folder.
function playSound() { // function that plays the sound
audio.pause();
audio.currentTime = 0;
audio.play();
}
for (let i = 0; i < amount; i++) { // loop to play as many times you asked in "let amount "
setTimeout(playSound, 1200 * i); // 1200 = 1200 mseconds between each times the sound plays.
}
}
</script>
</html>

Audio Volume Slider

I need some help, I don't if im over complicating things but I basically have a music player im working on that has 2 tracks. and i have a volume slider im using. when i slide my slider the volume will change they way it should. but when i click on next for the next track to load the volume resets on the music player, . but my slider value stays the same and if i slide my volume afterwords it will update. how can i get the music player to automatically set its volume to my slider values from start when I click on next.
if this sound confusing i put all my code on here so you can check it out. theirs two players for each track so u can see what im talking about. basically if my silder is moved to 0 meaning no sound. each track should be on 0. so if click next, that track should be set to 0 automatically once its loaded.
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title> My audio test</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript" src="js/jquery11.js"></script>
<script>
jQuery(document).ready(function(){
i=0;
nowPlaying = document.getElementsByClassName('playsong');
nowPlaying[i].load();
volume =($(this).val(.3));
callMeta();
$('.play').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.stop').on('click', function() {
nowPlaying[i].pause();
callMeta();
});
$('.next').on('click', function() {
$.each($('audio.playsong'), function() {
this.pause();
});
++i;
nowPlaying[i].load();
nowPlaying[i].volume;
nowPlaying[i].play();
callMeta();
});
$('.prev').on('click', function() {
$.each($('audio.playsong'), function() {
this.pause();
});
--i;
nowPlaying[i].load();
nowPlaying[i].play();
callMeta();
});
function callMeta() {
var trackTitle = $(nowPlaying[i]).attr('data-songtitle');
$('.songtitle').html(trackTitle);
var trackArtist = $(nowPlaying[i]).attr('data-songartist');
$('.songartist').html(trackArtist);
var albumart = $(nowPlaying[i]).attr('data-albumart');
$('img.albumart').attr('src', albumart);
}
$("input[type=range]").val($(this).val()); // set value to 6
$('#volume-bar').change(function(evt) {
nowPlaying[i].volume =($(this).val()/100);
$('#newValue').html(nowPlaying[i].volume);
});
})
</script>
</head>
<body>
<audio class="playsong" controls="controls" data-songtitle="love and fluff" data-songartist="nelly" data-albumart= "img/0qXrGPz.jpg" src="Andy Mineo.mp3">
Your browser does not support html audio tag
</audio>
<audio class="playsong" controls="controls" data-songtitle="food for fat kids" data-songartist="chubby" data-albumart= "img/Lecrae_1600x16002-400x400.jpg" src="Derek Minor.mp3">
Your browser does not support html audio tag
</audio>
<img class="albumart" src="img/Aunrey-avatar.jpeg"></img>
<div class="songartist">song title goes here</div>
<div class="songtitle">song title goes here</div>
<div class="play">Play</div>
<div class="stop">Stop</div>
<div class="next">Next</div>
<div class="prev">Prev</div>
<div class="volume">Volume</div>
<input type="range" id="volume-bar" min="0" max="100" step="0.1" value="100">
<div id="newValue" value="0">0</div>
</body>
</html>
Perhaps the only thing needed is to apply the volume - that was already set - to the new called song, take a look in the changes:
$('.next').on('click', function() {
$.each($('audio.playsong'), function() {
this.pause();
});
++i;
nowPlaying[i].load();
nowPlaying[i].volume =($("#volume-bar").val()/100); //changed line
nowPlaying[i].play();
callMeta();
});
$('.prev').on('click', function() {
$.each($('audio.playsong'), function() {
this.pause();
});
--i;
nowPlaying[i].load();
nowPlaying[i].volume =($("#volume-bar").val()/100); //added line
nowPlaying[i].play();
callMeta();
});

html5 video and javascript combination fails

I am working on a HTML5 video functionality and I have a question in SO asking the approach to be followed.
Found some semi-helping articles on w3.org website but found a completely working example on jsfiddle.net
Please follow the link here
I am trying the same as follows in my local machine -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<link href="jquery-mobile/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
var video = document.getElementById('video').play();
var intervalRewind;
$(video).on('play', function () {
video.playbackRate = 1.0;
clearInterval(intervalRewind);
});
$(video).on('pause', function () {
video.playbackRate = 1.0;
clearInterval(intervalRewind);
});
$("#speed").click(function () { // button function for 3x fast speed forward
video.playbackRate = 3.0;
});
$("#negative").click(function () { // button function for rewind
intervalRewind = setInterval(function () {
video.playbackRate = 1.0;
if (video.currentTime == 0) {
clearInterval(intervalRewind);
video.pause();
} else {
video.currentTime += -.1;
}
}, 30);
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content">
<video id="video" controls>
<source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4">
<source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm" type="video/webm">
<source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv" type="video/ogg">
</video>
<button id="speed">Fast Forward</button>
<button id="negative">Rewind</button>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
I am not able to find out why and where this script is failing. Is jquerymobile a problem?
Expected: Both Forward and Reverse functionalities should work.
Actual: None of the two buttons are working.
Any help is very much appreciated.
Thanks in advance.
You script worked (more or less), all it took to make it work was to comment out setting playback rate on play event. It was interfering with setting playback rate after clicking fast-forward. Working example here http://jsfiddle.net/h9EVQ/32/
As to the script itself, you should realize, that your rewind implementation has some flaws. One of them is that video is actually paused the whole time, so user can't just press pause to stop rewinding. But that would be easily solvable. The other, bigger issue is, that while doing a rewind you hop back in time by .1 fraction. That may or may be not an issue for some setups/movies. For those shorter movies your rewind function might be to speedy.

Video with custom controls using HTML5 video and Javascript

I am trying to create an HTML5 video player without the default controls that will play/pause by simply clicking the video(or overlaying div). I want to hide the default controls completely. I want the user to only be able to pause/play by clicking on the video. Is this possible? My initial strategy was to overlay a transparent div above the element that would serve as my play/pause button. Below is the HTML and javascript I started, but need a little bit of help. Thanks everyone!
<!-- Video -->
<div style="height:980px;height:540px;">
<div style="z-index:100;position:absolute;">
<video id="myVideo" width="980" height="540" poster="http://d3v.lavalobe.com/voicecarousel/images/Carousel_Still.png" audio="muted" autoplay="true">
<source src="http://d3v.lavalobe.com/voicecarousel/video/CarouselWBG_v3.mp4" type="video/mp4">
</video>
</div>
<div id="imgPoster" style="height:300px; width:300px; background-color:red; z-index:500;position:absolute;"></div>
</div>
<!-- end Video -->
<!-- JAVASCRIPT FOR VIDEO PLAYER -->
<script type="text/javascript">
var videoEl = $('#myVideo');
playPauseBtn = $('#imgPoster');
playPauseBtn.bind('click', function () {
if (videoEl.paused) {
videoEl.play();
} else {
videoEl.pause();
}
});
videoEl.removeAttribute("controls");
</script>
<!-- END JAVASCRIPT FOR VIDEO PLAYER -->
There's no need for two id attributes in the video tag, and there's no need for a separate source tag if only using one file format, and the video and poster you are linking to does not exist.
Anyway, example below:
<video id="myVideo" width="980" height="540" poster="http://d3v.lavalobe.com/voicecarousel/images/myPoster.png" audio="muted" autoplay="true" src="http://d3v.lavalobe.com/voicecarousel/video/myVid.mp4" type="video/mp4">
</video>
<script type="text/javascript">
$("#myVideo").bind("click", function () {
var vid = $(this).get(0);
if (vid.paused) {
vid.play();
} else {
vid.pause();
}
});
</script>
EDIT: adding a fiddle : http://jsfiddle.net/SKfBY/
Had a quick look at your site, and the video is cool :-)
If you look closely you'll see that there are two jQuery files added, not really the problem here, but you only need one, the second one will make your page load slower.
Also not the problem, but you should consider using the HTML5 doctype like below, as the video element is HTML5, but most browsers will figure it out anyway.
The problem seems to be my fault, jsFiddle automagically inserts the $document.ready function, and I forgot it in my example, that's why it's not working for you.
Here is a complete rundown of how I would write it, I removed both instances of jQuery for you and replaced with Google's version of jQuery, wich is usually a better option, and also you should probably remove any scripts that you don't need, like removing swfObject if the site does not contain any flash files using swfobject etc.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="http://dev4.baytechlabs.com/Voice_Carousel/css/main/style.css"/>
<link rel="stylesheet" type="text/css" href="http://dev4.baytechlabs.com/Voice_Carousel/css/main/thickbox.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/main/cufon-yui.js" type="text/javascript"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/main/Pristina_400.font.js" type="text/javascript"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/main/MomsTypewriter_400.font.js" type="text/javascript"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/main/cufon-config.js" type="text/javascript"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/thickbox.js" type="text/javascript"></script>
<script src="http://dev4.baytechlabs.com/Voice_Carousel/js/swfobject.js" type="text/javascript"></script>
<script type="text/javascript" src="http://dev4.baytechlabs.com/Voice_Carousel/js/facebox/facebox.js"></script>
<link href="http://dev4.baytechlabs.com/Voice_Carousel/js/facebox/facebox.css" media="screen" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function() {
$("#myVideo").bind("click", function () {
var vid = $(this).get(0);
if (vid.paused) {
vid.play();
} else {
vid.pause();
}
});
});
</script>
</head>
<body>
<video id="myVideo" width="980" height="540" audio="muted" autoplay="true" src="http://d3v.lavalobe.com/voicecarousel/video/CarouselWBG_v3.mp4" type="video/mp4">
</video>
</body>
</html>
This code works for me:
function vidplay() {
var video = document.getElementById("video1");
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.textContent = "||";
} else {
video.pause();
button.textContent = ">";
}
}
function restart() {
var video = document.getElementById("video1");
video.currentTime = 0;
}
function skip(value) {
var video = document.getElementById("video1");
video.currentTime += value;
}
But setting the time to 0 rewound the video only; no playback. So I wanted the video to replay after rewinding, and came up with this:
function restart() {
var video = document.getElementById("video1");
var button = document.getElementById("play");
if (video.paused) {
}
else {
video.pause();
}
video.currentTime = 0;
video.play();
button.textContent = "||";
}
Here are the buttons:
<div id="buttonbar">
<button id="restart" onclick="restart();">[]</button>
<button id="rew" onclick="skip(-10)"><<</button>
<button id="play" onclick="vidplay()">></button>
<button id="fastFwd" onclick="skip(10)">>></button>
</div>
My two-cent's worth...
Cheers

Categories