How to pause previous audio function? - javascript

When I press the button, I want to play a song, when I press the second song a second time, and when the third one, the cycle repeats again, but the first song is shorter than the second one, and if you click many times, the long song plays simultaneously with its other copy. Is it possible to stop the previous music and move on to another?
Html:
< a id="Play">test< / a>
Script:
window.onload=function(){
let number = 0;
var t;
document.getElementById('Play').addEventListener('click',function(){
let audio = new Audio();
if ( number == 0 ) {
audio.src = '/assets/sound/test.mp3';
number = 1;
}
else
if ( number == 1 ) {
audio.src = '/assets/sound/curious&loony.mp3';
number = 0;
}
audio.autoplay = true;
});
}

sound.pause();
sound.currentTime = 0;
Use this for pause audio

Found a way.
How to:
<script>
var i = 1, player = new Audio();
player.src = "/assets/sound/sound1.mp3";
document.querySelector('#play-button').addEventListener('click', function(e) {
e.preventDefault();
if (i === 1) {
player.src = "/assets/sound/sound1.mp3";
i = 0;
} else if (i === 0) {
player.src = "/assets/sound/sound2.mp3";
i = 1;
}
player.play();
});
</script>
Play me harder

Related

Unable to pause audio after eventListener end

When first loading the code, the pause button works fine, it pauses the audio and changes the HTML class of the button inside, the button continues to work after using the previous/next buttons to go to another song, however after the eventListener is triggered the pause button stops working, it doesn't pause the songs but the HTML inside still changes.
Edit: After a little bit of further debugging I found that the pause button is only able to pause the first time a track is loaded, once the audio.addEventListener('ended', nextTrack); is triggered it is unable to pause/play any audio.
let audio = new Audio;
let playing = false;
let playpause = document.getElementById('play-pause');
let root = document.documentElement;
let songname = document.getElementById('name');
let next = document.getElementById('next');
let prev = document.getElementById('previous');
let index = 0;
songlist = [
{"name":"Love Again"
,"artist":"The Kid LAROI",
"path":"resources/music/love-again.mp3",
},
{
"name":"Always Do",
"artist":"The Kid LAROI",
"path":"resources/music/always-do.mp3",
},
{
"name":"Bye Bye",
"artist":"Juice WRLD",
"path":"resources/music/bye-bye.mp3",
},
{
"name":"Understand",
"artist":"BoyWithUke",
"path":"resources/music/understand.mp3",
}
]
function progress_animation(){
var currentTime = audio.currentTime;
var duration = audio.duration;
$('#progbar').stop(true, true).animate({ 'width': (currentTime + .25) / duration * 100 + '%' }, 250, 'linear');
window.requestAnimationFrame(progress_animation);
};
function load(index){
songname.textContent = `${songlist[index].artist} - ${songlist[index].name}`;
audio.src = songlist[index].path;
audio.load()
};
audio.addEventListener('ended', nextTrack);
$('#play-pause').click(function (){
if (!playing) {
Play()
playing = true
} else {
Pause()
playing = false
}
});
function nextTrack(){
if (index < songlist.length - 1) {
index++;
} else {
index = 0;
}
load(index);
};
function prevTrack(){
if (index > 0) {
index--;
} else {
index = songlist.length - 1;
}
load(index);
};
function Play() {
audio.play();
playing = true;
playpause.innerHTML = '<i class="fa-solid fa-pause"></i>';
};
function Pause() {
audio.pause()
playing = false;
playpause.innerHTML = '<i class="fa-solid fa-play"></i>';
};
The pause button still changes its HTML class and sets the "playing" variable to false/true depending on the state of "playing" but doesn't actually pause the song

Browser video flickers when switching clip [HTML, JS]

I want to have video clips that seamlessly transition from one to another(with idle animations). For starters, I wanted to use the normal browser player and just switch sources when one clip ends like this:
var videos = [
"video/1.webm",
"video/2.webm",
"video/3.webm",
"video/4.webm",
];
let i = 0;
const videoCount = videos.length;
const element = document.getElementById("video");
element.addEventListener('ended', myHandler, false);
function myHandler() {
i++;
if (i == videoCount) {
i = 0;
}
element.setAttribute("src", videos[i]);
element.autoplay = true;
// element.preload = true;
// element.muted = true;
element.load();
}
The problem is that there is a stutter/flicker or delay before a new clip starts playing(in chrome and firefox). The clips I have don't contain any black or empty frames(clips I have loop fine).
As far as I can tell it shows a blank screen for a frame or two.
Is there any way to preload the clips so they switch instantaneously?
The comments from Will and VC.One were leading me onto the right path. I created 2 video elements and instead of pushing and pulling the z-index I pushed it off screen with:
.hidden {
position: absolute;
left: -100vw;
}
I ended up using this:
var videos = [
"video/v1.webm",
"video/v2.webm",
"video/v3.webm",
// ...
];
var i = 0;
const videoCount = videos.length;
const v1 = document.getElementById("video");
const v2 = document.getElementById("video2");
v1.muted = true;
v2.muted = true;
v1.setAttribute("src", videos[i]);
v1.load();
v1.play();
i++;
v2.setAttribute("src", videos[i]);
v2.load();
v1.addEventListener('ended', vHandler, false);
v2.addEventListener('ended', vHandler, false);
function vHandler() {
if((i+1) == videoCount)
i = 0;
if(i % 2 == 0) {
i++;
v2.setAttribute("src", videos[i]);
v2.load();
v1.classList.remove("hidden");
v2.classList.add('hidden');
v1.play();
} else {
i++;
v1.setAttribute("src", videos[i]);
v1.load();
v2.classList.remove("hidden");
v1.classList.add('hidden');
v2.play();
}
}

Multiple audio players on the same page

I'm attempting to create two audio players on the same page. I've seen a similar question, which suggested, "filtering tasks for each audio element and audio value," but my player is so different than the one in that question that I'm not sure how to apply it to mine.
Whenever I try to play the first player, the second starts instead and breaks if I start clicking around. The scripts for the two players are in different files, I've already changed the IDs so there aren't duplicates, and I also tried changing the variable and function names thinking that maybe they were having some impact. Nothing has worked.
I'm using the same code for each player, but with a different prefix on each ID:
/* global $ */
var audio;
//Hide Pause
$('#pause').hide();
initAudio($('#playlist').find('li:first-child'));
$('#playlist').on('click', function(event) {
initAudio($(event.target));
});
// Initiate play sequence
function initAudio(element){
var recording = element.attr('data-id');
var title = element.text();
var artist = element.attr('data-artist');
//Create audio object
audio = new Audio('public/audio_files/'+ recording);
//Insert audio info
$('.artist').text(artist);
$('.title').text(title);
$('#playlist li').removeClass('active');
element.addClass('active');
// Set timer to 0
$('#duration').html('0:00');
// Maintain volume on song change
audio.volume = $('#volume').val() / 100;
}
//Play button
$('#play').click(function() {
audio.play();
showPause();
showDuration();
});
//Pause button
$('#pause').click(function() {
audio.pause();
showPlay();
});
//Next button
$('#next').click(function() {
audio.pause();
var next = $('#playlist li.active').next();
if(next.length == 0){
next = $('#playlist li:first-child');
}
showPause();
initAudio(next);
audio.play();
showDuration();
});
//Prev button
$('#prev').click(function() {
audio.pause();
var prev = $('#playlist li.active').prev();
if(prev.length == 0){
prev = $('#playlist li:last-child');
}
showPause();
initAudio(prev);
audio.play();
showDuration();
});
//Playlist song click
$('#playlist li').click(function() {
audio.pause();
initAudio($(this));
showPause();
audio.play();
showDuration();
});
//Volume control
$('#volume').change(function() {
audio.volume = parseFloat(this.value / 100);
});
// Show play button, hide pause
function showPlay() {
$('#play').show();
$('#pause').hide();
}
// Show pause button, hide play
function showPause() {
$('#play').hide();
$('#pause').show();
}
// Automatically play next song
function autoPlayNext() {
if(audio.currentTime == audio.duration) {
var next = $('#playlist li.active').next();
if(next.length == 0){
next = $('#playlist li:first-child');
}
showPause();
initAudio(next);
audio.play();
showDuration();
}
}
// Time/Duration
function showDuration() {
$(audio).bind('timeupdate', function() {
//Get hours and minutes
var s = parseInt(audio.currentTime % 60, 10);
var m = parseInt(audio.currentTime / 60, 10) % 60;
if(s < 10) {
s = '0' + s;
}
$('#duration').html(m + ':'+ s);
var value = 0;
if(audio.currentTime > 0){
value = Math.floor((100 / audio.duration) * audio.currentTime);
}
$('#progress').css('width', value + '%');
autoPlayNext();
});
}
// Skip time via progress bar click
$('#progress-bar').bind('click', function (e) {
var $div = $(e.target);
var offset = $div.offset();
var x = e.clientX - offset.left;
audio.currentTime = ((x / 2.3)/(100 / audio.duration)); /* length of progress-bar is 230px hence (x/2.3) */
});
Any insight?

video play loop play another ja

I need a video to play and loop seamlessly a defined number of times, then skip to a next video and loop seamlessly a defined number of times, and so forth until the playlist ends.
In one page, a user defines videos to be played, as well as how many times it will "loop" (or iterate). These are stored using session variables as:
$_SESSION["Exer[" .$x. "]"]
$_SESSION["Reps[" . $x. "]"].
I'm ignoring this aspect (the php stuff) currently
I have code that independently works, one that loops and one that plays playlists, but I can't seem to manage the merger of them together to achieve functionality. The code is as followed:
HTML
<video width="320" height="240" id="myVideo" autoplay="autoplay">
</video>
JavaScript
For looping:
<script>
var iterations = 1;
document.getElementById('iteration').innerText = iterations;
document.getElementById('myVideo').src = "Video/01.mp4";
myVideo.addEventListener('ended', function () {
if (iterations < 3) {
this.currentTime = 0;
this.play();
iterations ++;
document.getElementById('iteration').innerText = iterations;
}
}, true);
</script>
For playlist:
<script>
var videoSource = new Array();
videoSource[0] = "Video/01.mp4";
videoSource[1] = "Video/02.mp4";
videoSource[2] = "Video/03.mp4";
videoSource[3] = "Video/04.mp4";
var i = 0; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}
</script>
Any help is appreciated.
Please check this, this java script code will replay a video for mentioned number of times and then plays next video if exists in playlist:
var eachVdoLoop = 2;
var currentVdoLoop=0;
var videoSource = new Array();
videoSource[0] = "http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_1mb.mp4";
videoSource[1] = "https://www.w3schools.com/html/mov_bbb.mp4";
var videoCount = videoSource.length;
var vdoIndex=0;
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
nextVideo();
function myHandler() {
currentVdoLoop++;
if(currentVdoLoop < eachVdoLoop)
{
document.getElementById("myVideo").play();
}
else
{
vdoIndex++;
currentVdoLoop=0;
nextVideo();
}
}
function nextVideo() {
if(vdoIndex == videoSource.length)
{
alert("Playlist ended!!!")
return;
}
document.getElementById("myVideo").setAttribute("src", videoSource[vdoIndex]);
document.getElementById("myVideo").play();
}
An working jsfiddle (fiddle updated)

HTML5 Audio - stop current play when another sound is started

I am using this method to play audio files when you click on an image:
http://jsfiddle.net/v97Kq/3/
function imageSwitch(_imgID, _imgStart, _imgStop, _soundFileMp3, _soundFileOgg) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.song = new Audio();
if (this.song.canPlayType("audio/mpeg"))
this.song.src = _soundFileMp3;
else
this.song.src = _soundFileOgg;
this.song.loop = true;
this.pos = 0;
this.e;
this.change = function () {
if (this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.song.play();
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.song.pause();
}
}
}
It works good! - but how can I get it to stop playing the currently playing sound when another link is clicked and another sound begins?
I found this solution to my issue above, works perfectly.
which I eventually found here:
<script>
var currentPlayer;
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
if(currentPlayer && currentPlayer != thissound) {
currentPlayer.pause();
}
if (thissound.paused)
thissound.play();
else
thissound.pause();
thissound.currentTime = 0;
currentPlayer = thissound;
}
</script>

Categories