HTML5/JavaScript audio playlist - javascript

I have found a nice tutorial on how to build a playlist using HTML5 and JavaScript in blog post HTML5 Audio and Video and how to make a playlist. I followed the instructions, but I did not get the correct outcome.
This code SHOULD play all three audio files in order and stop when the last song has ended, but it what it actually does is autoplay the first file then stops when the first file is completed. What did I do wrong?
<html>
<body>
<ul id="playlist">
<li class="active">
<a href="http://www.codenamejupiterx.com/song/soundtest.mp3">
soundtest
</a>
</li>
<li>
<a href="http://www.codenamejupiterx.com/song/soundtest2.mp3">
soundtest2
</a>
</li>
<li>
<a href="http://www.codenamejupiterx.com/song/soundtest3.mp3">
soundtest3
</a>
</li>
</ul>
<script>
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('#audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
audio[0].play();
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}
else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
</script>
</body>
</html>

1) JavaScript code is using jQuery (those $(...) statements), so it must be imported:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
...
2) The audio HTML element (the real "player") is missed:
<body>
<audio id="audio" preload="auto" tabindex="0" controls="" >
<source src="http://www.codenamejupiterx.com/song/soundtest.mp3">
</audio>
...
3) The code play only TWO songs. To play THREE:
...
len = tracks.length; //"-1" removed
...
4) The code play again and again the three songs. To stop it:
audio[0].addEventListener('ended',function(e){
current++;
if(current < len){
link = playlist.find('a')[current];
run($(link),audio[0]);
}
});

Using jQuery I do have achieved this by using the following control.
Add the audio Control tag with following parameters:
<audio id="audio1" controls="controls" autoplay="autoplay"> </audio>
And in JavaScript:
jQuery(function($) {
var supportsAudio = !!document.createElement('audio').canPlayType;
if (supportsAudio) {
url = URL.baseUrl + Books + authors + "/" + subject + "/data.json";
$.getJSON(url, function(data){
console.log("ddd"+JSON.stringify(data));
var index = 0,
trackCount = data.URL.length,
npAction = $('#npAction'),
npTitle = $('#npTitle'),
audioid = $('#audio1').bind('play', function() {
}).bind('ended', function() {
if((index + 1) < trackCount) {
index++;
loadTrack(index);
audioid.play();
}
else {
audioid.pause();
index = 0;
loadTrack(index);
}
}).get(0),
loadTrack = function(id) {
index = id;
audioid.src = data.URL[index].ayah;
};
loadTrack(index);
});
}
});

Related

HTML5 audio playlist opens up new tab when clicked in Meteor web app

I'm working on a web app in meteor and I'm trying to use the HTML5, CSS and Javascript audio playlist in my app:
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
#playlist,audio{background:#666;width:400px;padding:20px;}
.active a{color:#5DB0E6;text-decoration:none;}
li a{color:#eeeedd;background:#333;padding:5px;display:block;}
li a:hover{text-decoration:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio" preload="auto" tabindex="0" controls="" type="audio/mpeg">
<source type="audio/mp3" src="http://www.archive.org/download/bolero_69/Bolero.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
<ul id="playlist">
<li class="active">Ravel Bolero</li>
<li>Moonlight Sonata - Beethoven</li>
<li>Canon in D Pachabel</li>
<li>patrikbkarl chamber symph</li>
</ul>
When I try to click on the li to play a song it opens the file up in a new tab with the audio in white and a black background.
I was wondering if anyone knew how to fix this as I've been stuck on this issue for almost three days now.
Thanks,
Dillon Davis
.I've just loaded jQuery in the snippet you've provided, and that worked fine. No other changes were required.
Check below snippet:
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
audio[ 0 ].addEventListener( 'canplay', function( e ) {
this.play();
}, false );
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
}
#playlist,audio{background:#666;width:400px;padding:20px;}
.active a{color:#5DB0E6;text-decoration:none;}
li a{color:#eeeedd;background:#333;padding:5px;display:block;}
li a:hover{text-decoration:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio" preload="auto" tabindex="0" controls="" type="audio/mpeg">
<source type="audio/mp3" src="http://www.archive.org/download/bolero_69/Bolero.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
<ul id="playlist">
<li class="active">Ravel Bolero</li>
<li>Moonlight Sonata - Beethoven</li>
<li>Canon in D Pachabel</li>
<li>patrikbkarl chamber symph</li>
</ul>
Update: I've added play() method after player loaded audio
Update 2: I've moved .play() to canplay event.

Javascript: Play website background videos in series?

I'm designing a landing page with video background. I'd like to auto-play a series of background video clips (looping back to #1 when the sequence runs out, although I haven't tried to integrate this wrinkle yet). I pulled some sample code off a reputable webdev blog and adapted it, but currently to no effect (my initial video plays once with the desired effect, but gives way to its poster image, rather than the next clip). Relevant html and js below. Help much appreciated!
<div id="video-box">
<video class="landing-video" autoplay muted poster="./resources/media/images/Two-Swimmers.jpg">
<source src="./resources/media/video/Two-Swimmers.mp4" type="video/mp4" />
</video>
<div class="video-playlist">
</div>
</div>
<script type="text/javascript" src="video.js"></script>
video.js code:
( function() {
var videoPlayer = document.getElementById( 'video-box' ),
video = videoPlayer.getElementsByClassName( 'landing-video' )[0],
playlist = videoPlayer.getElementsByClassName( 'video-playlist' )[0],
source = video.getElementsByTagName( 'source' ),
linkList = [],
videoDirectory = './resources/media/video/',
currentVideo = 0,
allLinks = playlist.children,
linkNumber = allLinks.length,
i, filename;
function playVideo( index ) {
allLinks[index].classList.add( 'current-video' );
currentVideo = index;
source[0].src = videoDirectory + linkList[index] + '.mp4';
video.load();
video.play();
}
for ( i = 0; i < linkNumber; i++ ) {
filename = allLinks[i].href;
linkList[i] = filename.match( /([^\/]+)(?=\.\w+$)/ )[0];
}
video.addEventListener( 'ended', function () {
allLinks[currentVideo].classList.remove( 'current-video' );
nextVideo = currentVideo + 1;
if ( nextVideo >= linkNumber ) {
nextVideo = 0;
}
playVideo( nextVideo );
} );
} () );
I changed video to have a src attribute, and I used setAttribute in the ended event handler.
var video = document.querySelector('video');
var links = document.querySelectorAll('.video-playlist > a');
var i = 0;
video.addEventListener('ended', function() {
i++;
if (i >= links.length) {
current = 0;
}
var a = links.item(i);
a.className = 'current-video';
video.setAttribute('src', a.href);
video.play();
});
<div id="video-box">
<video class="landing-video" autoplay muted src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>
<div class="video-playlist">
</div>
</div>
I don't have your CSS so you can't see the <a> tags or the current-video class. I also don't have your video files so I grabbed some public videos for demonstration purposes.

Trying to Loop an HTML5 Video Array

I'm running this array that plays the video array, but ends abruptly and doesn't loop. Of course I tried the HTML video attribute loop and loop="true" and loop="loop"... with no avail..
I just want to loop'it t'night:
var videos =
[
[
"img/poster.png",
"img/trippyInk.mp4"
],
[
"img/poster.png",
"img/brothaDive.webm"
],
[
"img/poster.png",
"img/wtuD97H.webm"
],
[
"img/poster.png",
"img/ride.webm"
]
];
function switchVideo(n) {
if (n >= videos.length) n = 0;
var mp4 = document.getElementById("mp4");
var parent = mp4.parentNode;
document._video.setAttribute("poster", videos[n][0]);
mp4.setAttribute("src", videos[n][1]);
document._video.load();
document._video.play();
I tried this command, this also didn't work.
$('video').attr('loop','loop');
}
Thanks!
Update
The key to making a series of video loop is to add your loop logic to the ended event.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>vidArray</title>
</head>
<body>
<video id="vid" src="https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4" poster="https://glpjt.s3.amazonaws.com/so/av/vs2s3.png" controls width="480" height="auto">
Your browser sux, why haven't you upgraded to Chrome or Firefox? Do you live in a cave?
</video>
<script>
var poster = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.png"]
var videos = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4"]
var vid = document.getElementById("vid");
var n = videos.length;
var cnt = 0;
function playVideo(x) {
var png = poster[x];
console.log('poster: ' + png);
var mp4 = videos[x];
console.log('video: ' + mp4);
vid.setAttribute('poster', png);
vid.src = mp4;
vid.load();
vid.play();
}
vid.addEventListener('ended', next, false);
function next() {
cnt++;
if (cnt < n) {
playVideo(cnt);
} else {
cnt = 0;
playVideo(cnt);
}
}
</script>
</body>
</html>
I separated the arrays, it works. Added a button to cycle through the videos.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>vidArray</title>
</head>
<body>
<video id="vid" src="https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4" poster="https://glpjt.s3.amazonaws.com/so/av/vs2s3.png" loop controls width="480" height="auto">
Your browser sux, why haven't you upgraded to Chrome or Firefox? Do you live in a cave?
</video>
<button id="btn1">Next</button>
<script>
var poster = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.png"]
var videos = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4"]
var n = videos.length;
var cnt = 0;
function switchVideo(n) {
var vid = document.getElementById("vid");
var png = poster[n];
console.log('poster: ' + png);
var mp4 = videos[n];
console.log('video: ' + mp4);
vid.setAttribute('poster', png);
vid.src = mp4;
vid.load();
vid.play();
}
var btn1 = document.getElementById("btn1");
btn1.addEventListener('click', function(e) {
cnt++;
if (cnt < n) {
switchVideo(cnt);
} else {
cnt = 0;
switchVideo(cnt);
}
}, false);
</script>
</body>
</html>
I think you're looking for:
$('video').attr('loop','loop');

How to play all music continually from playlist?

I am trying to play music from playlist. Need javascript function to play dynamically all songs continually.
Simple Player
<audio id="audio" preload="auto" tabindex="0" controls="">
<source type="audio/mp3" src="music/demo.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
Playlist
<ul id="playlist">
<?php if($lists) { foreach ($lists as $key=> $list) { ?>
<li class="active">
<a src="music/<?php echo $list; ?>.mp3">
<?php echo $list; ?> </a>
</li>
<?php }}?>
</ul>
JavaScript
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('src');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
I have 3 songs in playlist but the problem is it only plays the first 2 songs and the player skip last song and repeat the playlist again without play the last song.
You are increasing the current index before checking if it is the last one that is actually being played. Do this:
audio[0].addEventListener('ended',function(e){
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
current++; // <-- Increment after the check
}
run($(link),audio[0]);
});

Playlist with <audio> JavaScript

I'm creating a personal small website and I want to play some songs on it. What I've tried to do is the following:
<script type="text/javascript">
var i=1;
var nextSong= "";
var audioPlayer = document.getElementById('audio');
audioPlayer.onended = function(){
i++
nextSong = "Music/"+i+".mp3";
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}
</script>
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
However, I can't get this to work. It just plays the first song and doesn't execute the JS. I've tried alerting the state of i for example but it doesn't do anything.
Try this:
<script type="text/javascript">
var i=1;
var nextSong= "";
function setup() {
document.getElementById('audio').addEventListener('ended', function(){
i++;
nextSong = "Music/"+i+".mp3";
audioPlayer = document.getElementById('audio');
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
</body>
Amendment needed on this answer. You need to also identify the audio player, otherwise this won't work...
<script type="text/javascript">
function setup() {
var i=1;
var nextSong= "";
audioPlayer = document.getElementById('audio');
document.getElementById('audio').addEventListener('ended', function(){
i=i+1;
nextSong = "m"+i+".mp3";
audioPlayer.src = nextSong;
audioPlayer.load();
audioPlayer.play();
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="m1.mp3" controls="controls" autoplay="autoplay" align=""> </audio>
</body>
var i=1; var nextSong= ""; function setup() { document.getElementById('audio').addEventListener('ended', function(){ i++; nextSong = "Music/"+i+".mp3"; audioPlayer = document.getElementById('audio'); audioPlayer.src = nextSong; audioPLayer.load(); audioPlayer.play(); if(i == 37) // this is the end of the songs. { i = 1; } }, false); }

Categories