If playing an MPEG Dash video using dash.js, is it possible to make it loop, i.e. when the video has downloaded fully, replay the downloaded content, without having to download any more data or possibly just raising the resolution if possible, but this is not essential.
The standard code for displaying this is:
<div>
<video id="videoPlayer"></video>
</div>
<script src="https://cdn.dashjs.org/v2.0.0/dash.all.min.js"></script>
<script>
(function(){
var url = "./Videos/146252.mpd";
var player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector("#videoPlayer"), url, true);
})();
</script>
The video element has a loop attribute. Have you tried setting it?
Related
Okay, I'm losing my mind here.
I'm trying to code a very simple player just for myself -- something crude but functional.
<button onclick="javascript:PlayAudio();">Play</button>
<script>
var audio = new Audio();
audio.src = "file.mp3"; // this file is in the same directory as the html page
var PlayAudio = function()
{
audio.play();
};
</script>
Should work, right? I know it's not the BEST way to do it, but here's the thing: I've rewritten this code a couple hundred times and nothing seems to be working. There aren't even any error codes/exceptions/whatever that I can find. The browser says it's loaded the file just fine. What's even weirder is when I check the paused member in the audio object, no matter how many times I call the play() method, it still returns true.
When I load the page just as a file in my browser, lo and behold, it plays! Just fine! But if I were to change the onclick event to audio.play();, it doesn't work anymore. I want to run this on a server though.
I promise you there is no additional code. No JQuery, no weird server plugins (not even PHP!). Just Apache, Windows, nothing else.
And I know the browser can play the audio because when I copy audio.src and go to the address, it'll play just fine. Even the protocol is fine; the HTTP:/// address is not trying to load the File:/// address and vice versa. (I need the audio to play as a DOM so I can randomize the audio file later on; I'm just trying to get my browser to play one stinkin' file in the first place.)
I know I can do this in HTML with some JavaScript, but I know this can work in pure javascript too (ignoring the <button>) because I've done this before a LONG time ago. So what changed?
I've also tried to load the definitions using window.onload, but that doesn't work neither.
So... what the heck? I'm am stupid or something? I can accept that; I just need to know.
I think it's because of the path to the mp3 file. Also, separate your HTML from JavaScript code like so:
HTML
<button id="btn">Play</button>
JavaScript
const btnSound = document.querySelector('#btn');
btnSound.addEventListener('click', () => {
const sound = new Audio('./file.mp3') // assuming it's in the directory
sound.play();
});
If you're trying to create a dynamic audio element in pure Javascript...
Create a div on your document to act as container for the dynamic tag
in JS, create the audio element then add to page (via adding it to Div container)
Then you can try a code setup like this...
<div id="container">
<button onclick="PlayAudio('file.mp3')">Play</button>
<div>
<script>
//#create new audio tag
var myAudioElement = document.createElement( "audio");
myAudioElement.setAttribute("controls", "true" );
//myAudioElement.setAttribute("id", "myAudioTag"); //# if you'll need access "by ID"
//# add element to page DOM
document.getElementById('container').appendChild( myAudioElement );
function PlayAudio ( inputURL) //# input is a String like "file.mp3"
{
myAudioElement.setAttribute("src", inputURL);
myAudioElement.play();
}
</script>
Note: To run the playAudio() function without clicking a button just call:
PlayAudio ( "someOtherFile.mp3" );
PS: Below is an example of a "better" approach. Better here means less headaches (more intuitive) but it uses the HTML that you want to avoid. Notice no .src is specified because you can still use JS to update such property by code.
<!DOCTYPE html>
<html>
<body>
<h1>Test Audio Playback </h1>
<audio id="myAudioTag" controls> <source src=" " type="audio/mpeg"> </audio>
<br>
<button onclick="PlayAudio();"> Play </button>
</body>
<script>
var audio = document.getElementById("myAudioTag");
audio.src = "file.mp3"; // this file is in the same directory as the html page
function PlayAudio() { audio.play(); }
//# call this function whenever track must be changed
//# example use: changeAudio( "https://example.com/files/song2.mp3" );
function changeAudio( inputURL) //is a String of some other mp3 file
{
audio.src = inputURL;
audio.play();
}
</script>
</html>
Write your code like this
<button onclick="PlayAudio();">Play</button>
<script>
var PlayAudio = function()
{
var audio = new Audio("file.mp3")
audio.play();
};
</script>
If it still does not work then also try to write onClick
Where I can read information and see examples of loading chunks into html5 video?
Scenario:
1. User starts play a large video.
2. 10-20 seconds of the video should be downloaded.
3. If user watches first 10 seconds then next 10 seconds should be downloaded. Thus, there will be no load if the user looks only the first 9 seconds of video.
If we use this scenario it will reduce server load (in some cases).
For example:
Try to watch video on YouTube. They work like this. Try to load half video (~3 mins) and start watch it from beginning. Other part of video will not be downloaded until you reach special point (~ 50 seconds before the downloads point, in my case).
I can't find any controls of buffering in html5 video. Also I can't find any controls of buffering in popular html5 based video players like VideoJs, JPlayer.
Does somebody know how to do it?
I can't find any controls of buffering in html5 video.
The .buffered property of the HTMLMediaElement interface, and the TimeRanges object which you can get back from that, don’t give you direct control over buffering, but can give you some control over the user experience at least. For a simple case that uses them, here’s some sample code:
<!doctype html>
<html>
<head>
<title>JavaScript Progress Monitor</title>
<script type="text/javascript">
function getPercentProg() {
var myVideo = document.getElementsByTagName('video')[0];
var endBuf = myVideo.buffered.end(0);
var soFar = parseInt(((endBuf / myVideo.duration) * 100));
document.getElementById("loadStatus").innerHTML = soFar + '%';
}
function myAutoPlay() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.play();
}
function addMyListeners(){
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('progress', getPercentProg, false);
myVideo.addEventListener('canplaythrough', myAutoPlay, false);
}
</script>
</head>
<body onload="addMyListeners()">
<div>
<video controls
src="http://homepage.mac.com/qt4web/sunrisemeditations/myMovie.m4v">
</video>
<p id="loadStatus">MOVIE LOADING...</p>
</div>
</body>
</html>
That code is from a detailed Controlling Media with JavaScript guide over at the Safari Developer site. There’s also another good Media buffering, seeking, and time ranges how-to over at MDN.
If you really want more direct control over buffering, you need to do some work on the server side and use the MediaSource and SourceBuffer interfaces.
Appending .webm video chunks using the Media Source API is a good demo; code snippet:
var ms = new MediaSource();
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(ms);
ms.addEventListener('sourceopen', function(e) {
...
var sourceBuffer = ms.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
sourceBuffer.appendBuffer(oneVideoWebMChunk);
....
}, false);
I'm just getting started here with javascript and have made this.
I have made a codepen that shows the two issues I am having
1) there are two duplicate videos being loaded in, when I delete one of the video tags it prevents the randomize button from working or any video from loading up. I am only trying to have one video load in.
2) In the codepen I have a button that clicks to randomize but instead I am trying to have the video wrapped with an tag so that the video can be clicked to initiate the randomize. Whenever I try and do this I get an undefined error or the videos will not load in =/
Play video
<div class="video-label"></div> <!-- loads in top video (only want one video) -->
<video loop autoplay> <!-- loads in bottom video (only want one video) -->
Your browser does not support the <code>video</code> element.
</video>
If you click on the codepen you will hopefully be able to see where the two videos are being loaded in and where the click tag is. Any help is greatly appreciated!! I've been trying to figure it out all night :/
Here is the codepen
Codepen
Thanks in advance!
You can create a html5 video tag using javascript by following this logic:
var videoelement = document.createElement("video");
videoelement.setAttribute("id", "video1");
var sourceMP4 = document.createElement("source");
sourceMP4.type = "video/mp4";
sourceMP4.src = "http://zippy.gfycat.com/SpottedDefensiveAbalone.mp4";
videoelement.appendChild(sourceMP4);
var sourceWEBM = document.createElement("source");
sourceWEBM.type = "video/webm";
sourceWEBM.src = "http://zippy.gfycat.com/MinorGregariousGrub.webm";
videoelement.appendChild(sourceWEBM);
$('.video-label').html(videoelement);
var video = document.getElementById("video1");
video.play();
This code is creating a video tag and including it into your div (.video-label), then the video starts automatically. This is working without the random stuff (the same url is used everytime), so you can update it at your convenience. Try to remove the video in you html file, it works now:
<video loop autoplay>
Your browser does not support the <code>video</code> element.
</video>
Here is a link where you can download your code updated with working solution (without randomization):
http://tests.krown.ch/Codepen.zip
Also when you click on your video div (.video-label), the video tag will be deleted and created back (but with same url, you just need to update video url with your randomize stuff)
In this line you find any video tags on the page and try to copy it's content into div:
var $video = $('video');
...
$('.video-label').html($video.get(0).outerHTML);
But if you delete video from the page there will be nothing to copy. You need to move video tag inside div in first place. Or create it dynamically, not by copying, when user clicks link.
Im trying to make a video player work in all browsers. There is
more then one video and every time you click on demo reel it plays the
video and if you click the video 1 the other video plays. How can i
make them both work in all browsers? Here is my html and javascript
html
<video id="myVideo" controls autoplay></video>
<div>
Demo Reel</div>
video 1</div>
</div>
javascript
function changeVid1() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/demoreel.mp4"
}
function changeVid2() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/video1.mp4";
}
After you switch the source of the video, you need to run .load() on it to force it to load the new file. Also, you need to provide multiple formats, because there is no video codec supported by all browsers.
First, set up your sources like this:
var sources = [
{
'mp4': 'http://video-js.zencoder.com/oceans-clip.mp4',
'webm':'http://video-js.zencoder.com/oceans-clip.webm',
'ogg':'http://video-js.zencoder.com/oceans-clip.ogv'
}
// as many as you need...
];
Then, your switch function should look like this:
function switchVideo(index) {
var s = sources[index], source, i;
video.innerHTML = '';
for (i in s) {
source = document.createElement('source');
source.src = s[i];
source.setAttribute('type', 'video/' + i);
video.appendChild(source);
}
video.load();
video.play(); //optional
}
See a working demo here.
This gives the browser a list of different formats to try. It will go through each URL until it finds one it likes. Setting the "type" attribute on each source element tells the browser in advance what type of video it is so it can skip the ones it doesn't support. Otherwise, it has to hit the server to retrieve the header and figure out what kind of file it is.
This should work in Firefox going back to 3.5 as long as you provide an ogg/theora file. And it will work in iPads, because you only have one video element on the page at a time. However, auto-play won't work until after the user clicks play manually at least once.
For extra credit, you can append a flash fallback to the video element, after the source tags, for older browsers that don't support html5 video. (i.e., IE < 9 - though you'll need to use jQuery or another shim to replace addEventListener.)
How can I get the first frame of a video file in javascript as an image?
It can be done with HTML 5 video and canvas tags:
HTML:
<input type="file" id="file" name="file">
<video id="main-video" controls>
<source type="video/mp4">
</video>
<canvas id="video-canvas"></canvas>
Javascript:
var _CANVAS = document.querySelector("#video-canvas");
var _CTX = _CANVAS.getContext("2d");
var _VIDEO = document.querySelector("#main-video");
document.querySelector("#file").addEventListener('change', function() {
// Object Url as the video source
document.querySelector("#main-video source").setAttribute('src', URL.createObjectURL(document.querySelector("#file").files[0]));
// Load the video and show it
_VIDEO.load();
// Load metadata of the video to get video duration and dimensions
_VIDEO.addEventListener('loadedmetadata', function() {
// Set canvas dimensions same as video dimensions
_CANVAS.width = _VIDEO.videoWidth;
_CANVAS.height = _VIDEO.videoHeight;
});
_VIDEO.addEventListener('canplay', function() {
_CANVAS.style.display = 'inline';
_CTX.drawImage(_VIDEO, 0, 0, _VIDEO.videoWidth, _VIDEO.videoHeight);
});
});
View demo
Just add the video tag to the page with no controls and no auto-play.
<video width="96" height="54" class="clip-thumbnail"> ... </video>
Drawback is that users can play the video by right clicking the thumbnail and selecting "play" in the context-menu. To avoid that you'd need a little javascript listening for click events and cancelling them (removing context-menu from thumbnails).
As mentioned, Javascript is not able to do this.
If you want to create thumbnails for your videos you have to create the thumbnail server side and then simply serve up the image on the client as you would any other image.
My method of choice for accomplishing this is the ffmpeg decoder. It can handle a multitude of file formats and is able to do what you want. So if you have a video named hello.avi, you might do:
ffmpeg -itsoffset -1 -i /path/to/hello.avi -vcodec mjpeg -vframes 1 -an -f rawvideo -s 200x150 /path/to/hello.jpg
You can run this command (fixing the paths and dimensions...) with whatever server-side language you are using and it would create a thumbnail of the video file.
Javascript is not capable of doing this.
It may be possible if the video is a file selected by the user into an <input type="file">, you can get the base-64 video data using the FileReader API:
https://developer.mozilla.org/en-US/docs/DOM/FileReader
From there you're just left with the extremely intractable problem of decoding the video and somehow picking out and rendering a single frame, in javascript. Alternatively, you could just include the entire video as the "thumbnail preview" (I assume that's why you're doing this?), as demonstrated here:
http://hacks.mozilla.org/2009/12/file-drag-and-drop-in-firefox-3-6/
Not sure about the compatability of that last example though, or how well it work with larger video files (I hear you can easily bump up against URL length restrictions)