Play audio one by one - javascript

I have a list of audio files. How to make them play one by one? Right now If I click button play, they are playing all together.
const audioList = [ 'audio1', 'audio2', 'audio3', 'audio4', 'audio5' ]
let button = document.querySelector('#btnPlay').addEventListener('click', e=>{
audioList.forEach(element => {
let audio1 = new Audio(element);
audio1.play();
});

You can achive this by using the audio element's 'ended' event and change the audio's src after end of each song.
my html file:
<audio src=""></audio>
<button></button>
my js file:
const songs = [ 'audio1', 'audio2', 'audio3', 'audio4', 'audio5' ]
const audio = document.querySelector('audio');
const button = document.querySelector('button');
let songIndex = 0;
audio.src = songs[songIndex]
audio.addEventListener('ended', () => {
songIndex++;
if(songIndex >= songs.length) return;
audio.src = songs[songIndex]
audio.play()
})
document.addEventListener('click', () => audio.play())
Codepen demo : https://codepen.io/PatrykBuniX/pen/GRgGGyr
I hope it helped you! :D

Related

Video Player Local Storage For Each Video

i have movie website and my video player local storage just saving one video src.
i want to use different src for each movie video
window.addEventListener("unload", () => {
let setDuration = localStorage.setItem(
"duration",
`${mainVideo.currentTime}`
);
let setSrc = localStorage.setItem(
"src",
`${mainVideo.getAttribute("src")}`
);
});
window.addEventListener("load", () => {
let getDuration = localStorage.getItem("duration");
let getSrc = localStorage.getItem("src");
if (getSrc) {
mainVideo.src = getSrc;
mainVideo.currentTime = getDuration;
}
});

Is there something wrong with my code in my .js file for the pause button?

This is my current code for a music player im building for my portfolio. I am having an issue getting the button to pause. the music does play so that is not an issueyour text
const music = document.querySelector('audio');
const prevBTN = document.getElementById('prev');
const playBTN = document.getElementById('play');
const nextBTN = document.getElementById('next');
// Check if Playing
let isPlaying = false;
// Play
function playSong() {
let isPlaying = true;
playBTN.classList.replace('fa-play', 'fa-pause');
playBTN.setAttribute('title', 'Pause');
music.play();
}
// Pause
function pauseSong() {
let isPlaying = false;
playBTN.classList.replace('fa-pause', 'fa-play');
playBTN.setAttribute('title', 'Play');
music.pause();
}
// Play or Pause Event Listener
playBTN.addEventListener('click', () => (isPlaying ? pauseSong() : playSong()));
I have tried changing the names of attributes
In your functions, you say let isPlaying = .... This creates a new variable in the lexical scope of the function, not changing the global variable.
// Play
function playSong() {
isPlaying = true;
playBTN.classList.replace('fa-play', 'fa-pause');
playBTN.setAttribute('title', 'Pause');
music.play();
}
// Pause
function pauseSong() {
isPlaying = false;
playBTN.classList.replace('fa-pause', 'fa-play');
playBTN.setAttribute('title', 'Play');
music.pause();
}
remove the let and you'll be fine
Note that this doesn't account for when you get to the end of the song, where isPlaying will still be true.

JW Player getCurrent Function is not working

I am trying to add a button click event in JW Player to seek 10 seconds forward from current frame. But default getCurrent() function is not working.
Here is my code -
jwplayer('#myElement');
const forwardDisplayButton = (<HTMLElement>forwardContainer.querySelector('.jw-icon-rewind'));
const forwardControlBarButton = (<HTMLElement>forwardContainer.querySelector('.jw-icon-rewind'));
[forwardDisplayButton, forwardControlBarButton].forEach(button => {
button.onclick = () => {
player.seek((player.getPosition() + 10));
}
})
And Here is my error -
player.getPosition is not a function
Thank you in advance

How can I play only one song on a page [duplicate]

I have 10 audio players with simple html audio tags on a html5 page.
No jquery, no special audio js plugins, etc...
Does anyone has a simple script in js to pause all other players when the current player is playing ?
I don't want to use js plugins because i want to keep a simple audio html code.
you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.
document.addEventListener("play", function(evt) {
if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) {
this.$AudioPlaying.pause();
}
this.$AudioPlaying = evt.target;
}, true);
Mixing both previous answers that didn't work, i've used that. I just added && window.$_currentlyPlaying != evt.target and all is working.
Also i've created a gist with this and other goodies for audio tags. javascript-audio-tags
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
$("audio").on("play", function() {
var id = $(this).attr('id');
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
$("video").on("play", function() {
var id = $(this).attr('id');
$("video").not(this).each(function(index, video) {
video.pause();
});
});
I don't know if it is because of Chrome updates, but the previous answers did not work for me. I modified a bit of the code here and came up with this:
document.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
I don't know why, but the widow.addEventListener was not working for me, but I liked the idea of having the currentPlaying variable stored in the window element instead of having to create it outside of the listener prior to using it.
I made a player at the bottom and changed the src every time the user clicks on play
this is just one way of doing it
HTML
<audio src="tracks/track1.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio src="tracks/track2.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio src="tracks/track3.mp3" type="audio/mp3" class='audios'></audio>
<i class='fas fa-play'></i>
<i class='far fa-pause-circle'></i>
<i class='fas fa-stop'></i>
<audio class='main-audio' controls>
<source src="#" type="audio/mp3">
</audio>
JavaScript
const audios_with_src = document.querySelectorAll('.audios')
const play = document.querySelectorAll('.fa-play')
const pause = document.querySelectorAll('.fa-pause-circle')
const stop = document.querySelectorAll('.fa-stop')
const main_player = document.querySelector('.main-audio')
for(let i =0; i < audios_with_src.length; i++) {
play[i].addEventListener('click', (e) => {
main_player.src = audios_with_src[i].src;
main_player.play()
})
pause[i].addEventListener('click', () => {
main_player.pause()
})
stop[i].addEventListener('click', () => {
main_player.pause()
main_player.currentTime = 0; // there is no stop() function so had to do this
})
}
Best solution rewritten regarding ECMA 2022:
document.addEventListener('play', (event) => {
const audios = [...document.getElementsByTagName('audio')];
audios.forEach((audio) => audio !== event.target && audio.pause());
}, true);
You can even try this solution, if you don't want to loop through
var previousAudio;
document.addEventListener('play', function(e){
if(previousAudio && previousAudio != e.target){
previousAudio.pause();
}
previousAudio = e.target;
}, true);

Clicking multiple time on Button, Multiple audio play (Older sounds overlap new) in JavaScript

When I click on button, audio start. But when I click the button multiple times, multiple audio playing simultaneously.
HTML CODE
<button id = 'bt'> Click Me </button>
JavaScript Code
<script type="text/javascript">
url = 'song.mp3';
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(my, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
</script>
What I'm thinking as solution-
Before creating new click event, destroy last event fist then create new one.
When user click second, it check if cureentTime == 0, then play audio else start again or nothing happen.
Thanks to Gurpreet, your solution work.
On each click I'm creating a new audio element thats why multiple audio are playing.
Simply I saved my audio to a variable and passed to playFunc.
url = 'song.mp3'
const myAudio = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
playFunc(myAudio, 3);
});
function PlayFunc(target, RepeatCount) {
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else
target.removeEventListener('ended', soundFunc);
}
target.addEventListener('ended', soundFunc)
target.play();
}
Just de-register the click event handler in the click event handler. In order to do this, you'll need a named function.
btn.addEventListener('click', doPlay);
function doPlay(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
btn.removeEventListener('click', doPlay); // <-- de-register the handler
}
You can disable the button until the audio clip is over.
const url = 'http://www.noiseaddicts.com/samples_1w72b820/4927.mp3';
const my = new Audio(url);
var btn =document.getElementById('bt');
btn.addEventListener('click', function(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
playFunc(audioElement, 3);
});
function playFunc(target, RepeatCount) {
btn.disabled=true;
var soundFunc = function(){
RepeatCount--;
target.currentTime = 0;
if (RepeatCount>0)
target.play();
else{
target.removeEventListener('ended', soundFunc);
btn.disabled=false;
}
}
target.addEventListener('ended', soundFunc)
target.play();
}

Categories

Resources