Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  167] [ 5]  / answers: 1 / hits: 23883  / 8 Years ago, mon, september 5, 2016, 12:00:00

I want to create an audio background player where user can only click on image to play or stop the playback. I have trouble creating or rewirting existing codes to make a playlist for it, that automatically plays next song when previous is finished. I want to do it in vanilla js.

Here is what I have so far:

https://jsfiddle.net/rockarou/ad8Lkkrj/



var imageTracker = 'playImage';

swapImage = function() {
var image = document.getElementById('swapImage');
if (imageTracker == 'playImage') {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_pause_01.png';
imageTracker = 'stopImage';
} else {
image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_play_01.png';
imageTracker = 'playImage';
}
};

var musicTracker = 'noMusic';

audioStatus = function() {
var music = document.getElementById('natureSounds');
if (musicTracker == 'noMusic') {
music.play();
musicTracker = 'playMusic';
} else {
music.pause();
musicTracker = 'noMusic';
}
};

More From » html

 Answers
18

here is the trick to trigger next song:



music.addEventListener('ended',function(){
//play next song
});


How to play another song on same audio tag:



 music.pause();
music.src = new url;
music.load();
music.play();


Now here is a cool example of a playlist in html5, you can load each song at the time, case some clients (mobile) will not be happy when you consume the traffic, in next example all audios are loaded at same time to have a smooth transition from song to song,
loading the songs:



//playing flag 
var musicTracker = 'noMusic';
//playlist audios
var audios = [];
$(.song).each(function(){
var load = new Audio($(this).attr(url));
load.load();
load.addEventListener('ended',function(){
forward();
});
audios.push(load);
});
//active track
var activeTrack = 0;


Highlighting witch song is playing, with a bit of jquery, yeah, case yeah I'm lazy, lazy:



var showPlaying = function()
{
var src = audios[activeTrack].src;
$(.song).removeClass(playing);
$(div[url=' + src + ']).addClass(playing);
};


Fiddle here



Note: If the sound's doesn't play, manually check if audio url's are accessible


[#60809] Friday, September 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;