I have 5 div boxes that play a certain track on click (using data attributes), however, I can't seem to figure out how to pause the previous track on next click. The audio plays on top of each other.
Javascript:
var audio = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];
var music = document.querySelector('#container');
music.addEventListener('click', function(evt){
if(evt.target.tagName === "DIV"){
var index = evt.target.getAttribute('data-index');
var sound = new Audio(audio[index]);
sound.play();
audio.forEach(function(x){
if(x !== sound){
sound.pause();
}
})
}
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<section id="container">
<div data-index="0"><p>40's</p></div>
<div data-index="1"><p>50's</p></div>
<div data-index="2"><p>60's</p></div>
<div data-index="3"><p>70's</p></div>
<div data-index="4"><p>80's</p></div>
<div data-index="5"><p>90's</p></div>
<div data-index="6"><p>2000's</p></div>
<div data-index="7"><p>2010's</p></div>
</section>
<script src='script.js'></script>
</body>
</html>
sound will always refers to the most recently clicked sound, never to the one that was playing before. The easiest solution is probably to keep a variable playing that tracks the audio object that is currently playing. That way when a new sound is played, you have a reference to the old one that you can pause. That could look something like this
var audio = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];
var music = document.querySelector('#container');
var playing = undefined;
music.addEventListener('click', function(evt){
if(evt.target.tagName === "DIV"){
var index = evt.target.getAttribute('data-index');
var sound = new Audio(audio[index]);
if (playing) playing.pause();
sound.play();
playing = sound;
}
});
Another option is for you to just keep an array of audio objects and track the index of the currently playing audio. That could look like this. This may be preferable because it will keep the place of paused songs.
var audioNames = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];
var audio = [];
for (var a in audioNames) {
audio.push(new Audio(a));
}
var music = document.querySelector('#container');
var playingIndex = undefined;
music.addEventListener('click', function(evt){
if(evt.target.tagName === "DIV"){
var index = evt.target.getAttribute('data-index');
var sound = audio[index];
if (playing) audio[playingIndex].pause();
sound.play();
playingIndex = index;
}
});
Related
<html>
<body>
<audio autoplay id ="audio_1" src = "./Dusty.wav"></audio>
<audio loop id = "audio_2" src = "./Dusty3.wav"></audio>
<audio loop id = "audio_3" src = "./Dusty2.wav"></audio>
<!-- <input type = "button" value = "play" onClick="audiofun();" -->
</body>
<script>
// audiofun()
// {
var audio = document.getElementById("audio_1");
var audio2 = document.getElementById("audio_2");
var audio3 = document.getElementById("audio_3");
// audio2.pause();
// audio3.pause();
audio.addEventListener("ended", function () {audio2.play();})
audio2.addEventListener("ended", function () {audio3.play();})
// }
</script>
</html>
When I run this code audio2.play() is continuously playing and audio3.play is not at all playing. can anyone put light on my error... thanks in advance
i feel like your problem comes from the property "loop" in your audio tag. Maybe you should try:
<audio id = "audio_2" src = "./Dusty3.wav"></audio>
<audio id = "audio_3" src = "./Dusty2.wav"></audio>
And add a event listener on your first, then second audio.
var audio = document.getElementById("audio_1");
var audio2 = document.getElementById("audio_2");
var audio3 = document.getElementById("audio_3");
document.getElementById('audio_1').addEventListener('ended',audio_1Handler,false);
function audio_1Handler(e) {
audio2.play();
}
document.getElementById('audio_2').addEventListener('ended',audio_2Handler,false);
function audio_2Handler(e) {
audio3.play();
}
the snippet above is highly inspired of : this post
Hopefully this helps you.
Feel free to ask any further questions !
I am trying to make a html5 player with a playlist so that when a song ends the next one begins automatically.
Im using jQuery.
This is my Javascript:
$(function(){
var player = $('#player')
var index = 0
var CurrentTime = 0
var tracks = [ {'source' : 'audio1.mp3'},
{'source' : 'audio2.mp3'},
{'source' : 'audio3.mp3'}]
var CurrentTrack = tracks[index]
function updateCookie(){
Cookies.set('trackIndex', index)
Cookies.set('time', CurrentTime)
}
//Check if the user has been here before
if(!!Cookies.get('trackIndex')){
updateCookie()
}
else {
index = Cookies.get('trackIndex')
CurrentTime = Cookies.get('time')
}
function playerSetUp(){
player[0].currentSrc = CurrentTrack.source
player[0].currentTime = CurrentTime
}
player.bind('ended',function(){
index++
player[0].currentSrc = CurrentTrack.source
console.log($('#player').currentSrc)
player[0].load()
player[0].play()
})
player.bind('pause',function(){
CurrentTime = $('#player').currentTime
updateCookie()
})
})
And this is my html:
<html>
<head>
<title>Mixtape</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-
3.2.1.min.js"></script>
<script src="js.cookie.js"></script>
<script type="text/javascript" src="player.js"></script>
<head>
<body>
<audio controls autoplay id='player'>
<source src="audio1.mp3">
Fallback
</audio>
</body>
I want to create a player that imitates the behavior of an analog audio tape. I want it to play one song after the other and when you close the page and open it again the player will continue from the last track and time you paused it.
The problem is my code above doesn't respond to the events.
What am I doing wrong?
You have three errors in your code, the event listeners are working.
Use:
//Check if the user has been here before
if(!Cookies.get('trackIndex')){
updateCookie()
CurrentTrack = tracks[index]
}
else {
index = Cookies.get('trackIndex')
CurrentTime = Cookies.get('time')
CurrentTrack = tracks[index]
}
(Just one "!"). And you need to update "CurrentTrack" each time you modify your "index", because you just set currentTrack one time.
And:
playerSetUp();
player.bind('ended', function() {
index++;
index = index % tracks.length
CurrentTrack = tracks[index]
player[0].currentSrc = CurrentTrack.source
console.log(player[0].currentSrc)
player[0].load()
player[0].play()
})
player.bind('pause', function() {
CurrentTime = player[0].currentTime
updateCookie()
})
You need to call playerSetUp() and index = index % tracks.length so that your index wont be bigger than your tracks array.
One more thing: player[0].currentSrc is readonly. You need to use player[0].src.
I have urls of several audio files like this:
example.net/{num}.mp3
And I would like to play them one after the other without a delay between them.
I tried having two audio elements with preload=true and switching between them, but I still have a delay.
Any ideas ?
I'd like to see the actual code of what you have so far, because I'm not 100% sure what "switching between them" means, but I wrote the following example which starts the next file playing before the first one finishes. You specify a set amount of "overlap", and it starts playing the next file JSFiddle: http://jsfiddle.net/76xqhupw/4/
const OVERLAP_TIME = 1.0; //seconds
const song1 = document.getElementById('audio1');
const song2 = document.getElementById('audio2');
song1.addEventListener("timeupdate", function() {
if (song1.duration - song1.currentTime <= OVERLAP_TIME) {
song2.play();
}
});
song1.play();
This is just relevant to playing the next audio element instantly, since you said you already had two audio elements, but if I'm missing something let me know.
<html>
<head>
<title>Subway Maps</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body onload="onload();">
<video id="idle_video" width="1280" height="720" onended="onVideoEnded();"></video>
<script>
var video_list = ["Skydiving Video - Hotel Room Reservation while in FreeFall - Hotels.com.mp4",
"Experience Conrad Hotels & Resorts.mp4",
"Mount Airy Casino Resort- Summer TV Ad 2.mp4"
];
var video_index = 0;
var video_player = null;
function onload(){
console.log("body loaded");
video_player = document.getElementById("idle_video");
video_player.setAttribute("src", video_list[video_index]);
video_player.play();
}
function onVideoEnded(){
console.log("video ended");
if(video_index < video_list.length - 1){
video_index++;
}
else{
video_index = 0;
}
video_player.setAttribute("src", video_list[video_index]);
video_player.play();
}
</script>
</body>
for refrence how to display multiple videos one by one dynamically in loop using HTML5 and javascript
You can use ended event, Array.prototype.shift() to set src of element to next item within array, if array .length is greater than 0, call .load(), .play()
var url = "example.net/"
var type = ".mp3";
var n = [0,1,2,3,4,5];
var audio = document.querySelector("audio");
audio.onended = function() {
if (n.length) {
this.src = url + n.shift() + type;
this.load();
this.play();
}
}
audio.src = url + n[0] + type;
audio.load();
audio.play();
im making a slideshow using videos and images with an array in
javascript i have a next button and previous button. The videos work
with the buttons and play and everything just when i added the
pictures into the array and keep clicking next they wont show up not
sure how to do this. Also every time you hit next or previous the
caption updates to match whats displaying, that also works fine. also
my videos only work in chrome any idea on how to fix that too? here is
my html and javascript code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript homework 2</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="mainImg">
<h2 id="caption">movie1</h2>
<video id="myVideo" src="video/movie1.mp4" type="video/mp4"/></video>
</div>
<div id="controls">
<div id="playToggle" class="player-button">Play</div>
</div>
<div id="links">
<ul>
<a onClick="nextPhoto();" href="#">Next</a>
<a onClick="prePhoto();" href="#">Previous</a>
</ul>
</div>
</body>
<script src="js/javascript.js"></script>
</html>
// JavaScript Document
/*---Global varibales--*/
var currentImage = 0;
var count = 0;
var videos = new Array("movie1", "movie2", "movie3","Dk1", "Dk2", "Dk3");
var captions = new Array("movie1", "movie2", "movie3", "Dark Knight 1", "Dark Knight 2", "Dark Knight 3");
var video = document.createElement("video");
var playPauseButton = document.getElementById('playToggle');
function switchVideo() {
video.setAttribute('src',videoPaths[CurrentVideos]);
video.onload = function() {
currentVideo++;
if (currentVideo >= videoPaths.length) {
currentImage = 0;
}
}
}
function changeVideo(movie)
{
var thisVideo = "video/"+videos[movie]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[movie];
count = movie;
}
function nextPhoto()
{
count++;
if(count==videos.length)
{
count = 0;
}
var thisVideo = "video/"+videos[count]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[count];
}
function prePhoto()
{
count--;
if(count < 0)
{
count = videos.length-1;
}
var thisVideo = "video/"+videos[count]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[count];
}
playPauseButton.onclick = function() {
if (myVideo.paused) {
myVideo.play();
this.innerHTML = "Pause";
} else {
myVideo.pause();
this.innerHTML = "Play";
}
};
In the nextPhoto() function you set the current image or video by using
var thisVideo = "video/"+videos[count]+".mp4";
This works for mp4 files but for nothing else. I recommend you add the file extensions to your array like so.
var videos = ["movie1.mp4", "image1.png"]; // and so on....
I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>