[javascript] HTML 5 video or audio playlist

Can I use a <video> or <audio> tag to play a playlist, and to control them?

My goal is to know when a video/song has finished to play and take the next and change its volume.

This question is related to javascript html audio video

The answer is


You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation


I created a JS fiddle for this here:

http://jsfiddle.net/Barzi/Jzs6B/9/

First, your HTML markup looks like this:

<video id="videoarea" controls="controls" poster="" src=""></video>

<ul id="playlist">
    <li movieurl="VideoURL1.webm" moviesposter="VideoPoster1.jpg">First video</li>
    <li movieurl="VideoURL2.webm">Second video</li>
    ...
    ...
</ul>

Second, your JavaScript code via JQuery library will look like this:

$(function() {
    $("#playlist li").on("click", function() {
        $("#videoarea").attr({
            "src": $(this).attr("movieurl"),
            "poster": "",
            "autoplay": "autoplay"
        })
    })
    $("#videoarea").attr({
        "src": $("#playlist li").eq(0).attr("movieurl"),
        "poster": $("#playlist li").eq(0).attr("moviesposter")
    })
})?

And last but not least, your CSS:

#playlist {
    display:table;
}
#playlist li{
    cursor:pointer;
    padding:8px;
}
#playlist li:hover{
    color:blue;                        
}
#videoarea {
    float:left;
    width:640px;
    height:480px;
    margin:10px;    
    border:1px solid silver;
}?

jPlayer is a free and open source HTML5 Audio and Video library that you may find useful. It has support for playlists built in: http://jplayer.org/


I optimized the javascript code from cameronjonesweb a little bit. Now you can just add the clips into the array. Everything else is done automatically.

<video autoplay controls id="Player" src="http://www.w3schools.com/html/movie.mp4" onclick="this.paused ? this.play() : this.pause();">Your browser does not support the video tag.</video>

<script>
var nextsrc = ["http://www.w3schools.com/html/movie.mp4","http://www.w3schools.com/html/mov_bbb.mp4"];
var elm = 0; var Player = document.getElementById('Player');
Player.onended = function(){
    if(++elm < nextsrc.length){         
         Player.src = nextsrc[elm]; Player.play();
    } 
}
</script>

Yep, you can simply point your src tag to a .m3u playlist file. A .m3u file is easy to construct -

#hosted mp3's need absolute paths but file system links can use relative paths
http://servername.com/path/to/mp3.mp3
http://servername.com/path/to/anothermp3.mp3
/path/to/local-mp3.mp3

-----UPDATE-----

Well, it turns out playlist m3u files are supported on the iPhone, but not on much else including Safari 5 which is kind of sad. I'm not sure about Android phones but I doubt they support it either since Chrome doesn't. Sorry for the misinformation.


It has been done there : http://www.jezra.net/projects/pageplayer


You can add an event listener with 'ended' as the first param

Like this :

https://stackoverflow.com/a/2880950/6839331


I wasn't satisfied with what was offered, so here's my proposal, using jQuery :

            <div id="playlist">
                <audio id="player" controls preload="metadata" volume="1">
                  <source src="" type="audio/mpeg">
                  Sorry, this browser doesn't support HTML 5.0
                </audio>
                <ul></ul>
            </div>

            <script>
                var folder = "audio";
                var playlist = [
                    "example1.mp3",
                    "example2.mp3"
                ];
                for (var i in playlist) {
                    jQuery('#playlist ul').append('<li>'+playlist[i]+'</li>');
                }

                var player = document.getElementById('player');
                var playing = playlist[0];
                player.src = folder + '/' + playing;

                function display(id) {
                    var list = jQuery('#playlist ul').children();
                    list.removeClass('playing');
                    jQuery(list[id]).addClass('playing');
                }

                display(0);

                player.onended = function(){
                    var ind_next = playlist.indexOf(playing) + 1;

                    if (ind_next !== 0) {
                        player.src = folder + '/' + playlist[ind_next];
                        playing = player.src;
                        display(ind_next)
                        player.play();
                    }
                }
            </script>

You only have to edit the playlist array, and you're done


There's no way to define a playlist using just a <video> or <audio> tag, but there are ways of controlling them, so you can simulate a playlist using JavaScript. Check out sections 4.8.7, 4.8.9 (especially 4.8.9.12) of the HTML5 spec. Hopefully the majority of methods and events are implemented on modern browsers such as Chrome and Firefox (latest versions, of course).


To add to the current answers, here is a playlist of videos which works with separate subtitle files. At the end of the playlist, it will go to endPage

<video id="video" controls autoplay preload="metadata">
   <source src="vid1.mp4" type="mp4">
   <track id="subs" label="English" kind="subtitles" srclang="en" src="sub1.vtt" default>
</video>

<script type="text/javascript">
var endPage = "duckduckgo.com";
var playlist = [
    { 
        'file': 'vid2.mp4',
        'subtitle': 'sub2.vtt'
    },{
        'file': 'vid3.mp4',
        'subtitle': 'sub3.vtt'
    }
]
var i = 0;
var videoPlayer = document.getElementById('video');
var subtitles = document.getElementById('subs');
videoPlayer.onended = function(){
    if(i < playlist.length){
        videoPlayer.src = playlist[i].file;
        subtitles.src = playlist[i].subtitle;
        i++;
    } else {
        console.log("We are leaving")
        document.location.href = endPage;
    }
}
</script>

Try this solution, it takes an array of soundtracks and plays all of them, playlist-style, and even loops the playlist. The following uses a little Jquery to shorten getting the audio element. If you do not wish to use Jquery, replace the first line of the javascript with var audio = document.getElementById("audio"); and it will work the same.

Javascript:

var audio = $("#audio")[0];
var tracks = {
    list: ["track_01.mp3", "track_02.mp3", "track_03.mp3"], //Put any tracks you want in this array
    index: 0,
    next: function() {
        if (this.index == this.list.length - 1) this.index = 0;
        else {
            this.index += 1;
        }
    },
    play: function() {
        return this.list[this.index];
    }
}

audio.onended = function() {
    tracks.next();
    audio.src = tracks.play();
    audio.load();
    audio.play();
}

audio.src = tracks.play();

HTML:

<audio id="audio" controls>
    <source src="" />
</audio>

This will allow you to play as many songs as you want, in playlist style. Each song will start as soon as the previous one finishes. I do not believe this will work in Internet Explorer, but it's time to move on from that ancient thing anyways!

Just put any songs you want into the array tracks.list and it will play all of them one after the other. It also loops back to the first song once it's finished with the last one.

It's shorter than many of the answers, it accounts for as many tracks as you want, it's easily understandable, and it actually loads the audio before playing it (so it actually works), so I thought I would include it here. I could not find any sound files to use in a running snippet, but I tested it with 3 of my own soundtracks on Chrome and it works. The onended method, which detects the ended event, also works on all browsers except Internet Explorer according to caniuse.

NOTE: Just to be clear, this works with both audio and video.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to audio

How to prevent "The play() request was interrupted by a call to pause()" error? Creating and playing a sound in swift How to play or open *.mp3 or *.wav sound file in c++ program? How to playback MKV video in web browser? Play audio as microphone input HTML embed autoplay="false", but still plays automatically Autoplay an audio with HTML5 embed tag while the player is invisible Playing mp3 song on python Javascript Audio Play on click Play sound on button click android

Examples related to video

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66? How to make a movie out of images in python HTML5 Video autoplay on iPhone How do we download a blob url video Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM How to embed new Youtube's live video permanent URL? How to disable auto-play for local video in iframe Writing an mp4 video using python opencv How to extract 1 screenshot for a video with ffmpeg at a given time? Bootstrap 3 - Responsive mp4-video