How to create a play a video in Javascript - javascript

I'm creating a chrome extension (not for new tab) and want to auto play a muted video every time the user goes to a specific website.
I attempted to try it out in CodePen and it's still not playing the video.
// Video BG
let videoContainer = document.createElement("video");
videoContainer.id = "video";
videoContainer.style.backgroundColor = "rgba(236,55,55,.5)";
videoContainer.style.zIndex = "-1";
videoContainer.style.width = "100%";
videoContainer.style.height = "100vw";
videoContainer.style.marginTop = "50x";
videoContainer.style.position = "fixed";
videoContainer.style.top = "0";
videoContainer.src =
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images";
//videoContainer.type = "video/mp4";
videoContainer.muted = true;
videoContainer.autoplay = true;
videoContainer.loop = true;
videoContainer.controls = false;
document.body.append(videoContainer);
I'm pretty new to coding by the way. Thanks to all who can help.

No problem if you are new, you can check in the MDN official documentation, we have the HTMLMediaElement play() method attempts to begin playback of the media. It returns a Promise which is resolved when playback has been successfully started.
You can try using this async function to do that! ;)
const videoElem = document.querySelector("#video");
const playButton = document.querySelector("#playbutton");
playButton.addEventListener("click", handlePlayButton, false);
playVideo();
async function playVideo() {
try {
await videoElem.play();
playButton.classList.add("playing");
} catch (err) {
playButton.classList.remove("playing");
}
}
function handlePlayButton() {
if (videoElem.paused) {
playVideo();
} else {
videoElem.pause();
playButton.classList.remove("playing");
}
}

It seems the source,
videoContainer.src = "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images";
was in fact not '.mp4' but a '.gif'. I tried changing the type as 'video/'asterik'' to accept all video file types, but it failed to display the '.gif' file.
My fix: Simply changing the video source to be an ".mp4" type. i.e "myvideo.mp4"
Questions:
Is 'video/*' not the correct way to include all video formats?
Is a '.gif' not a video file?
Thanks to all that helped!

Related

HTML5 video element request stay pending forever (on chrome in mobile) when toggle over front-rare camera

I'm developing an app where users can capture photo using a front/rare camera. it working perfectly but when toggle over camera front/rare var playPromise = videoStream.play() is gone in pending state. some times promise get resolve, the camera is working sometimes not.
this issue occurs only in chrome browser not in mozila and firefox
try {
stopWebCam(); // stop media stream when toggle over camera
stream = await navigator.mediaDevices.getUserMedia({video: true});
/* use the stream */
let videoStream = document.getElementById('captureCandidateId');
videoStream.srcObject = stream;
// videoStream.play();
var playPromise = videoStream.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
// Automatic playback started!
// Show playing UI.
})
.catch(error => {
// Auto-play was prevented
// Show paused UI.
});
}
};
} catch(err) {
/* handle the error */
console.log(err.name + ": " + err.message);
}
let stopWebCam = function (pictureType) {
setTimeout(()=>{
let videoStream = document.getElementById('captureCandidateId');
const stream = videoStream.srcObject;
if (stream && stream.getTracks) {
const tracks = stream.getTracks();
tracks.forEach(function(track) {
track.stop();
});
}
videoStream.srcObject = null;
}, 0)
}
Here, I drafted a piece of code for you, this is much more simple and smaller approach than what you are trying to do. I am just taking the stream from the video element and drawing it to canvas. Image can be downloaded by right clicking.
NOTE: Example does not work in StackOverflow
<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<script>
const player = document.getElementById('player');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
const constraints = {
video: true,
};
captureButton.addEventListener('click', () => {
// Draw the video frame to the canvas.
context.drawImage(player, 0, 0, canvas.width, canvas.height);
});
// Attach the video stream to the video element and autoplay.
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
player.srcObject = stream;
});
</script>
If you want, you can also make some edits according to your needs, like:
Choose which camera to use
Hide the video stream
Add a easier method to download the photo on your device
You can also add a functionality to upload the photo straight to the server if you have one

Create a popup media player using JS?

I have been trying to make an audio player that has basic controls allowing audio to be played instead of a video. It needs to be viewed in PIP mode, as well. Here is my code so far:
var audio = document.createElement('audio'); // The Audio
var canvas = document.createElement('canvas'); // New Canvas To Contain Video
canvas.width = canvas.height = 512;
var video = document.createElement('video'); // Create Video
video.srcObject = canvas.captureStream(); // Make Video Reflect The Canvas
video.muted = true;
function showPictureInPictureWindow() {
const image = new Image();
image.crossOrigin = true;
image.src = [...navigator.mediaSession.metadata.artwork].pop().src;
image.decode();
canvas.getContext('2d').drawImage(image, 0, 0, 512, 512);
video.onloadedmetadata = function() {
video.play();
video.requestPictureInPicture();
};
}
window.VID = video;
window.AU = audio;
function playAudio() {
audio.src = "mysong.mp3";
// Update Media Session metadata
navigator.mediaSession.metadata = new MediaMetadata({
title: "Audio Title",
artist: "MEEEEEEE",
album: "LOOOL",
artwork: [{src: "graphics/128x128.png", sizes: "128x128", type: "image/png"}]
});
// Play audio
audio.play();
// Show track album in a Picture-in-Picture window
showPictureInPictureWindow();
}
window.VID.requestPictureInPicture();
playAudio();
Any help that you can give me would be very much appreciated. (I already have the pause and play functions but I didn't include them for message size)
PS: (I don't know why, but earlier I was getting an error that said "JavaScript exception: Failed to execute 'requestPictureInPicture' on 'HTMLVideoElement': Metadata for the video element are not loaded yet" and now I have no errors at all... and no music either...)
PPS: (I fixed some of the bugs... and now I have the original error again.)
I have the same problem as you, but I have solved it
My solution:
My guess is that the video data did not load successfully when the RequestPicturePicture function was executed
So you can execute the RequestPicturePicture function in the loadedData function

How to set the value of a cookie to 0 if <audio> source changes in Javascript

so, i've been toying with this for a little bit and i am awful with JS but i feel like I'm really close to figuring it out, so even just being pointed in the right direction would help.
Right now i have audio that plays persistently across page changes via cookies, and that part is working great. however when the song source changes, I would really like the song to start back at 0. (Right now it just keeps playing at the value the cookie currently holds.)
This is what I have so far:
var song = document.getElementsByTagName("audio")[0];
var source = song.currentSrc;
var originalSource = source;
var played = false;
var tillPlayed = getCookie("timePlayed");
function update()
{
if(!played){
if(tillPlayed){
if (source == originalSource){
song.currentTime = tillPlayed;
song.play();
played = true;
}
else {
song.currentTime = 0;
cong.currentTime = tillPlayed;
song.play();
played = true;
}
}
else {
song.play();
played = true;
}
}
else {
setCookie('timePlayed', song.currentTime);
}
}
setInterval(update,0);
And it just makes the song not play at all.
It looks like it should be correct, and i'm just at a loss at this point as to why it's not working.
Anyone have any tips on getting it to function?
EDIT:
Ive moved the extra code into the original function, this is what I have at this point. It's still not working, the music will play again, but it doesn't reset the cookie.
The cookie does function as it should, I am just trying to change it
It looks like you are assigning the value from the cookie to song.currentTime immediately after resetting it with
song.currentTime = 0;
song.currentTime = tillPlayed;
Depending on your overall implementation you can solve that a couple ways as described in the comments in this variant of your solution:
var song = document.getElementsByTagName("audio")[0];/* orgiinal source song of the html player */
var source = getCookie("mySong");
if (source) /* You may different/additional logic for your exact use case*/
song.currentSrc = source /*Set audio player's source */
else
source = song.currentSrc; /*Save audio player source */
var originalSource = source;
var played = false;
var tillPlayed = getCookie("timePlayed");
function update()
{
if(!played)
{
if(tillPlayed)
{
if (source == originalSource) /* Note this this will only detect if the audio has since we came into the page. */
{
song.currentTime = tillPlayed;
song.play();
played = true;
}
else
{
song.currentTime = 0;
/* Since we just reset we do not want to retrieve the existing value in the cookie*/
/* cong.currentTime = tillPlayed; */
setCookie('timePlayed', song.currentTime); /* Store the reset value in the cookie. If the condition at the end is removed, you don't need to do this here. */
setCookie('mySong', song.currentSrc);
song.play();
played = true;
}
}
else
{
song.play();
played = true;
}
}
/* If it does not interfere with existing logic,
consider removing the else and always storing the value in the cookie here.
*/
else
{
setCookie('timePlayed', song.currentTime);
setCookie('mySong', song.currentSrc);
}
}
setInterval(update,0); /* Note that values of < 10ms resolve to 10ms */
Hope that helps

'Sounds' folder not loading correctly to localhost

Good afternoon,
I've been following this tutorial to make a simple (!) html5 canvas game. I've been using the error console on Safari to help troubleshoot, but I can't figure this one out; I have an 'img' folder, containing all artwork, and a 'sounds' folder, containing all sounds.
All assets are loaded with the assetLoader and checked before the page loads - if something is missing or labelled incorrectly, it won't load.
The sounds 'do' play - the theme music runs fine, and sound effects trigger approx 60% - 70% of the time (jump sound, collide sound etc) but the folder hasn't loaded correctly. If I check the 'resources' tab, 'sounds' is now called 'Other', and if I click on any of the mp3's in that folder, I get the message 'An error occurred trying to load the resource'.
The assetLoader part of the code looks like this:
var assetLoader = (function() {
this.sounds = {
'bg' : 'sounds/theme.mp3',
'jump' : 'sounds/fart.mp3',
'gameOver' : 'sounds/gameOver.mp3',
'ding' : 'sounds/ding.mp3'
};
Then I have a var to check the total number of sound assets:
var numSounds = Object.keys(this.sounds).length;
Then I have this function to check the state:
function _checkAudioState(sound) {
if (this.sounds[sound].status === 'loading' && this.sounds[sound].readyState === 4)
{ assetLoaded.call(this, 'sounds', sound);
}
}
Finally, I have a downloadAll function that looks like this:
this.downloadAll = function() {
var _this = this;
var src;
for (var img in this.imgs) {
if (this.imgs.hasOwnProperty(img)) {
src = this.imgs[img];
(function(_this, img) {
_this.imgs[img] = new Image();
_this.imgs[img].status = 'loading';
_this.imgs[img].name = img;
_this.imgs[img].onload = function() { assetLoaded.call(_this, 'imgs', img) };
_this.imgs[img].src = src;
})(_this, img);
}
}
for (var sound in this.sounds) {
if (this.sounds.hasOwnProperty(sound)) {
src = this.sounds[sound];
(function(_this, sound) {
_this.sounds[sound] = new Audio();
_this.sounds[sound].status = 'loading';
_this.sounds[sound].name = sound;
_this.sounds[sound].addEventListener('canplay', function() {
_checkAudioState.call(_this, sound);
});
_this.sounds[sound].src = src;
_this.sounds[sound].preload = 'auto';
_this.sounds[sound].load();
})(_this, sound);
}
}
}
return {
imgs: this.imgs,
sounds: this.sounds,
totalAssest: this.totalAssest,
downloadAll: this.downloadAll
};
})();
I've left the images in this block of code as they work fine, and I think the sounds should too, but for some reason they don't. I have read about potential mp3 compatibility problems with browsers and html5 canvas, but as the sounds are playing I'm not sure this is the issue. If anyone can offer any insight, that would be much appreciated.

How to use the VideoJS flash fallback for RTMP streaming?

I want to set up VideoJS to handle RTMP streaming using VideoJS-SWF player as flash-fallback, which does seem to have some support for it.
This is how I'd set up VideoJS for normal MP4 videos:
var tag = document.createElement("video");
tag.id = "vid1";
tag.controls = true;
tag.className = "video-js";
tag.preload = "auto";
tag.width = "640";
tag.height = "264";
tag.poster = "http://video-js.zencoder.com/oceans-clip.png";
var source1 = document.createElement("source");
source1.src = "http://video-js.zencoder.com/oceans-clip.mp4";
source1.type = "video/mp4";
tag.appendChild(source1);
// Add more sources, etc...
document.getElementById('player').appendChild(tag);
var player = _V_(tag, {width:640, height:264, techOrder:['flash', 'html5']}, function() {
var that = this;
this.addEvent('loadstart', function { that.play(); });
});
But how do you set up VideoJS to play an RTMP stream? Do you use the same tags, or is there some other way to specify the RTMP provider and stream url?
Just FYI - RTMP streaming is not yet available in VideoJS, but recent changes (like https://github.com/videojs/video.js/pull/605) indicate that it may be soon.
Pay attention to the feature request at https://github.com/videojs/video.js/issues/559 for updates.

Categories

Resources