How do I create a random video to play every time a user visits/reloads the page with Javascript?
For example, if one person were to go onto my domain, the iFrame would try to load any of the .mp4 files inside of my media file directory where it has like 4 different .mp4 videos. Here is my code below.
Code:
<source src="assets/media/lofi.mp4" type="video/mp4" />
<script type="text/javascript">
const video = document.currentScript.parentElement;
video.volume = 0.15;
function pause_resume() {
const button = document.getElementById("pause_resume_button");
if (video.paused) {
video.play()
button.textContent = "resume video";
} else {
video.pause()
button.textContent = "pause video";
}
}```
You need to use Math.random to choose a random video from a list.
Then add the chosen video url to the html element, and trigger the "play" event.
const videos = ["video1.mp4", "video2.mp4", /* ... */ "video30.mp4"]
const randomNumber = Math.floor(Math.random() * videos.length)
const currentVideo = videos[ randomNumber ]
const videoElement = document.getElementById('video');
videoElement.src = currentVideo
videoElement.play()
Related question: changing source on html5 video tag
Related
I'm making a random order video player, adapting code from here but the same video just keeps playing, even though I can see (from text above the video) that the random ordering is working. Live version is here.
Is the problem with the appendChild meaning the new video is end of a list but the first in list keeps playing? I tried replaceChild but that didn't work.
<script type="text/javascript">
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'carlos/one-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/two-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/three-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/four-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/five-carlostest.mp4'}]
];
// selecting random item from array as first to be played
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src){
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(){
var newRandom = videos[Math.floor(Math.random()*videos.length)];
newvideo(newRandom[0].src)
document.getElementById("monitor").innerHTML = "randomitem is " + newRandom[0].src;
}
})
</script>
Also, if anyone can tell me why the autoplay never works that'd be appreciated, though it's the least of my problems.
I have kinda found this solution for your video playing one after other. now in your JS file, now you just will need to add your video src path.
var vidElement = document.getElementById('video');
var vidSources = [
"https://lutins.co.uk/carlos/one-carlostest.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});
video {
width:350px;
}
<p>wowww you got it!</p>
<video src="https://lutins.co.uk/carlos/one-carlostest.mp4" id="video" autoplay muted playsinline></video>
Change the randomIt variable into a callback, only this way, it will generate new random number each time it get call.
// I have change randomitem into a function with ofcourse a proper name
var getRandomItem = function() {
return videos[Math.floor(Math.random()*videos.length)];
}
You should also call it properly like this:
//newvideo(randomitem[0].src) -> change it to
newvideo(getrandomItem().src)
There might also other adjustments requires for your code to work.
I am trying to create an HTML video playlist and currently I am using vid.onended to detect when a video is done playing (based of the current video src) and then play the next video when the video ends. This works perfectly for the first video but for some reason it never plays the second video and jumps straight to the third video.
My code:
//add video playlist functionality to auto play next video based on id
var vid = document.getElementById("urlVideo");
vid.onended = function() {
var video0 = "http://techslides.com/demos/sample-videos/small.mp4";
var video1 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
var video2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
if (vid.src = video0) {
vid.src = video1;
}
if (vid.src = video1) {
vid.src = video2;
}
};
<video id="urlVideo" width="100%" height="460" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
What am I doing wrong?
Edit:
Answer by Alen Toma works perfectly.
I Also managed to do it according to the current video source based on a comment by Quentin, For anyone else looking for how to do it explicitly with the current video source as the variable/condition, please see
https://jsfiddle.net/redlaw/qjb5h7e9/9/
I did make a small example below, it should help.
Have a look at this JSFiddle.
//add video playlist functionality to auto play next video based on id
var videoSrc = [
"https://media.w3.org/2010/05/sintel/trailer.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
]
var vid = document.getElementById("urlVideo");
var index = 0;
vid.addEventListener("ended", function() {
var currentSrc = videoSrc[index];
index += 1;
if (index >= videoSrc.length)
index = 0; // Make Loop and jump to the first video
vid.src = currentSrc;
vid.play();
console.log(currentSrc)
}, true);
<video id="urlVideo" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
you must use an event listener for your video player like this code:
var vid = document.getElementById("urlVideo");
vid.addEventListener("ended", function() { /* your code*/ }, true);
I am running the following code which changes the source of an html5 video at the end of each video, so that it constantly plays one video after another. After the first video finishes, it runs the second, then the third and eventually starts again from the beginning, resulting in an endless cycle. It also chooses a random starting point, but that is not important for my question.
In the code below you will only find two video sources but the final code would use around ten or so.
My problem is that there is a small pause between the end of a video and the beginning of the next one. I have made the background-color of the video tag red so that you will be able to see a red flash between the playback of each video.
I'm guessing that this could be solved by preloading all videos specified inside the javascript code. So what I would like to achieve is to preload only the next video in the list specified inside the javascript code when the current video is playing. So when video nr. 5 is playing, it should preload video nr. 6 etc..
Or is this not something that could be solved by effective buffering / preloading? I'm happy about any other suggestions as well..
var vidElement = document.getElementById('video');
var vidSources = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});
video { background-color: red }
<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="video" autoplay muted playsinline></video>
<p>(each video is just ~ 10 seconds)</p>
You can create video elements with preload attribute and add it to div containar like follows:
function initVideoElement(videoEl)
{
videoEl.playsinline = true;
videoEl.muted = false;
videoEl.preload = 'auto'; //but do not set autoplay, because it deletes preload
//loadedmetadata is wrong because if we use it then we get endless loop
videoEl.onplaying = function(e)
{
if(++nextActiveVideo == 2)
nextActiveVideo = 0;
//replace the video elements against each other:
if(this.inx == 0)
nextVideoElement = videoElements[1];
else
nextVideoElement = videoElements[0];
nextVideoElement.src = vidSources[nextActiveVideo];
nextVideoElement.pause();
};
videoEl.onended = function(e)
{
this.style.display = 'none';
nextVideoElement.style.display = 'block';
nextVideoElement.play();
};
}
var videoContainer = document.getElementById('videoContainer'),
nextActiveVideo = 0,
nextVideoElement,
videoElements =
[
document.createElement('video'),
document.createElement('video')
],
vidSources =
[
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
videoElements[0].inx = 0; //set index
videoElements[1].inx = 1;
initVideoElement(videoElements[0]);
initVideoElement(videoElements[1]);
videoElements[0].autoplay = true;
videoElements[0].src = vidSources[0];
videoContainer.appendChild(videoElements[0]);
videoElements[1].style.display = 'none';
videoContainer.appendChild(videoElements[1]);
video{background-color: red}
<div id="videoContainer"></div>
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';
}
};
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
[Here a non vanilla solution.] My playlist consists of four songs, they are named 0.mp3, 1.mp3, 2.mp3 and 3.mp3.
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<audio id="player" autoplay controls><source src="0.mp3" type="audio/mp3"></audio>
</body>
<script>
var x = 0;
var music = document.getElementById("player");
$("#player").bind("ended", function(){
x=x+1;
music.src = x%4 + ".mp3";
music.load();
music.play();
});
</script>
</html>
The playlist is repeated indefinetely.
Vanilla Javascript variant:
const audioArray = document.getElementsByClassName('songs'); //Get a list of all songs
let i = 0; //Initiate current Index
const player = document.getElementById('player'); //get the player
player.src = audioArray[i].getAttribute('data-url'); //set first Song to play
player.addEventListener('ended',function(){ //when a song finished playing
i++; //increase index
if (i < audioArray.length) { //If current index is smaller than count of songs
player.src = audioArray[i].getAttribute('data-url'); //set next song
return; // stop further processing of this function for now
}
// current index is greater than count of songs
i = 0; // therefore we reset the current index to the first available song
player.src = audioArray[i].getAttribute('data-url'); // and set it to be played
});
In this example you don't set an initial src for the audioplayers source-tag but instead have a list of class 'song'-items with an data-url attribute containing the url/path to the tracks.
I added comments to learn what and why this code is doing what it does.
Of course it could be better but it's a quick throwup of code ;)
I have the following code:
function playSound(source) {
document.getElementById("sound_span").innerHTML =
"<embed src='" + source + "' hidden=true autostart=true loop=false>";
}
<span id="sound_span"></span>
<button onclick="playSound('file.mp3');"></button>
Once you click play, the MP3 gets downloaded, than it starts to play. However, it can take a while if it has like 1 MB. What I need is a preloaded (just like you can do with the images). So when the page loads, the mp3 will be streamed and if, for instance, 10 seconds later, the user pressed the 'play' button, he won't have to wait until the mp3 gets downloaded first, as it is already streamed.
Any ideas? Thanks in advance for any tip!
You can preload using <audio /> for newer browsers. Set autoplay = false. For older browsers that don't support <audio />, you can use <bgsound />. To preload a sound, set the volume to -10000.
function preloadSound(src) {
var sound = document.createElement("audio");
if ("src" in sound) {
sound.autoPlay = false;
}
else {
sound = document.createElement("bgsound");
sound.volume = -10000;
}
sound.src = src;
document.body.appendChild(sound);
return sound;
}
That will get the sound in your browser's cache. Then to play it, you can keep doing what you are doing with <embed />. Or if you want to take advantage of HTML5 features, you can call .play() on the returned <audio /> element. You could even add a play method to the <bgsound />:
function loadSound (src) {
var sound = document.createElement("audio");
if ("src" in sound) {
sound.autoPlay = false;
}
else {
sound = document.createElement("bgsound");
sound.volume = -10000;
sound.play = function () {
this.src = src;
this.volume = 0;
}
}
sound.src = src;
document.body.appendChild(sound);
return sound;
}
Then use it like this:
var sound = loadSound("/mySound.ogg"); // preload
sound.play();
The only caveat is FireFox doesn't support mp3. You'll have to convert your files to ogg.
Working demo: http://jsfiddle.net/PMj89/1/
You can use the HTML5 <audio> element's preload attribute, and fall back on <embed>.