intersection observer works only for the first video - javascript

I need to pause a video if it is not in view
the below code works only for the first video in list
how to make it working for all .bvideo ?
<video class='bvideo' src='a.mp4' poster='a.jpg' preload='none' controls></video>
<video class='bvideo' src='b.mp4' poster='b.jpg' preload='none' controls></video>
<video class='bvideo' src='c.mp4' poster='c.jpg' preload='none' controls></video>
let io = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(!entry.isIntersecting){entry.target.pause();}
});
});
$(document).ready(function(){
io.observe(document.querySelector('.bvideo'));
});

Use querySelectorAll() method.
$(document).ready(function() {
let bvideos = document.querySelectorAll('.bvideo');
bvideos.forEach(bvideo => io.observe(bvideo));
});

Related

Why `muted` attribute on video tag is ignored in React?

Well, as counter-intuitive as it sounds, muted tag is somehow ignored; check out the snippet below,
first one is rendered with react, the second one regular html; inspect them with your dev tools, and you see the react on doesn't have muted attribute; I already tried muted={true}, muted="true" but non is working.
function VideoPreview() {
return (
<div className="videopreview-container">
React tag:
<video
className="videopreview-container_video"
width="320"
height="240"
controls
autoPlay
muted
>
<source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
);
}
ReactDOM.render(<VideoPreview />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<hr/>
Regular html:
<video
width="320"
height="240"
controls
autoplay
muted
>
<source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
This is actually a known issue which has existed since 2016.
The video will be muted correctly, but the property will not be set in the DOM.
You can find multiple workarounds in the GitHub issue, although there might be pros and cons with any of them.
As mentioned by #FluidSense it is an open bug since forever.
I could achieve it like this:
import React, { useRef, useEffect } from "react";
export default function Video({ src, isMuted }) {
const refVideo = useRef(null);
useEffect(() => {
if (!refVideo.current) {
return;
}
if (isMuted) {
//open bug since 2017 that you cannot set muted in video element https://github.com/facebook/react/issues/10389
refVideo.current.defaultMuted = true;
refVideo.current.muted = true;
}
refVideo.current.srcObject = src;
}, [src]);
return (
<video
ref={refVideo}
autoPlay
playsInline //FIX iOS black screen
/>
);
}
muted works if you type it as muted="true". Using the string true sends the attribute to the DOM now
Here is how I dealt with it using dangerouslySetInnerHTML:
import React, { Component } from "react";
export default class VideoComponent extends Component {
state = {
videoStr: "",
};
componentDidMount() {
const { src } = this.props;
const videoStr = `
<video autoplay loop muted>
<source src=${src} type="video/mp4" />
</video>
`;
this.setState({ videoStr });
}
render() {
return (
<div
className={this.props.className}
dangerouslySetInnerHTML={{ __html: this.state.videoStr }}
/>
);
}
}
I would also note that some browsers like Chrome might have a limit for the file size a video can be. I was running my own videos on my website and when I inspected the page and looked under Sources I did not find the video I had used and been looking for. This forced me to investigate further. I realized the video that I was running was about 10.4mb. It was large relative to the usual payload of a website so I lowered the size to around 5mb and the video appeared on my site.
Some other information about my steps to finding a solutions was that I was using my localhost to run my React app. I also ran my React app on Safari which surprisingly displayed my video even when the size was 10.4mb. I'm guessing that browsers have different criteria for video sizes.
I ran into the same problem, so I made a custom HTML element that adds the muted video. Here is the custom muted video:
class MutedVideo extends HTMLVideoElement {
constructor() {
super();
this.muted = true;
// I also noticed that you used autoplay, so I added it too.
this.autoplay = true;
}
}
customElements.define("x-muted", MutedVideo, { extends: "video" });
And here the video preview.
// Notice how I removed the muted and autoPlay props and added the 'is' prop
function VideoPreview() {
return (
<video
is="x-muted"
width="320"
height="240"
controls
src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4"
>
Sorry, your browser does not support the HTML video tag
</video>
);
}
Here is a working demo
from my own project. (WORK)
const Header = () => {
const [isMuted, setIsMuted] = useState(false);
return (
<div className="header">
<video src={headerBg} autoPlay loop muted={isMuted? true : false} />
<div className="container" >
<div className="btn-mute" onClick={() => setIsMuted(!isMuted)}/>
</div>
</div>
);
};

No video sound if removing attribute muted on html element video

I use the HTML video element. As source I use a .mp4 video with sound. On my video element there are a few attributes. Default I use the attribute muted so there is no sound. With some JavaScript I add or remove the attribute muted by clicking on a button. So this works, when I inspect my markup and click the button I can see how the attribute muted will be added or removed (check out my snippet below).
My problem is, that when removing it, there is no sound. If I start the video file in an video player on my laptop or open it directly in the browser, I can hear the sound. Due to many posts, it should be possible to toggle the sound with this solution. I don't know why it doesn't have sound only when I use it in my video element with adding/removing the attribute muted. Any ideas?
const $ctx = $('.video');
const $video = $ctx.find('.video__video');
const $toggleSound = $ctx.find('.video__toggle-sound');
$toggleSound.click(this.handleVideoSound.bind(this));
function handleVideoSound() {
const attr = $video.attr('muted');
if (typeof attr !== typeof undefined && attr !== false) {
$video.removeAttr('muted');
} else {
$video.attr('muted', '');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
<video class="video__video" autoplay loop muted playsinline poster="/assets/img/video-poster.png">
<source src="/assets/video/video.mp4" type="video/mp4">
</video>
<button class="video__toggle-sound">Toggle video sound</button>
</div>
Replace your handleVideoSound method with the below code
function handleVideoSound() {
const attr = $video.prop("muted");
$video.prop("muted", !attr);
}
Hope it will help you. Below is the working code snippet.
const $ctx = $(".video");
const $video = $ctx.find(".video__video");
const $toggleSound = $ctx.find(".video__toggle-sound");
$toggleSound.click(this.handleVideoSound.bind(this));
function handleVideoSound() {
const attr = $video.prop("muted");
$video.prop("muted", !attr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
<video class="video__video" autoplay loop muted playsinline poster="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg">
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", type="video/mp4" />
</video>
<button class="video__toggle-sound">Toggle video sound</button>
</div>

player.stop() dosen 't works on videojs

I'm trying to implement videojs with the IMA plugin, and i need to capture the stop and play event from a button outside the videobox in my react app.
The thing is i capture the event on my buttons and works fine, but they dosen t work when i want to stop the ADS.. why? Any clue?
i use this example
https://googleads.github.io/videojs-ima/examples/simple/
and i log the player.ima and return this, but i cant access to any element..
here is my code! thanks!
index.js
<video id="content_video"
class="video-js vjs-default-skin""
controls
>
<source src="//commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" ></source>
</video>
<script>
window.player = videojs
var player = window.player('content_video');
var options = {
id: 'content_video',
adTagUrl: 'http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=xml_vmap1&unviewed_position_start=1&cust_params=sample_ar%3Dpremidpostpod%26deployment%3Dgmf-js&cmsid=496&vid=short_onecue&correlator='
};
player.ima(options);
</script>
home.js
handlePlay = () => {
if(this.props.showPlay == 'block'){
const player = window.videojs(`#content_video`)
player.play() //only work on the video not in ads
} else {
const player = window.videojs(`#content_video`)
player.pause() //only work on the video not in ads
}
}

WebRTC pause and resume stream

I am trying to use WebRTC to build a web application that needs to pause/resume the video/audio stream when some events trigger. I have tried the getTracks()[0].stop() but I am not sure how to resume the stream. Are there any advice on that? thanks
getTracks()[0].stop() is permanent.
Use getTracks()[0].enabled = false instead. To unpause getTracks()[0].enabled = true.
This will replace your video with black, and your audio with silence.
Try it (use https fiddle for Chrome):
var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => pc1.addStream(video1.srcObject = stream))
.catch(log);
var mute = () => video1.srcObject.getTracks().forEach(t => t.enabled = !t.enabled);
var add = (pc, can) => can && pc.addIceCandidate(can).catch(log);
pc1.onicecandidate = e => add(pc2, e.candidate);
pc2.onicecandidate = e => add(pc1, e.candidate);
pc2.onaddstream = e => video2.srcObject = e.stream;
pc1.onnegotiationneeded = e =>
pc1.createOffer().then(d => pc1.setLocalDescription(d))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
.then(() => pc1.setRemoteDescription(pc2.localDescription))
.catch(log);
var log = msg => div.innerHTML += "<br>" + msg;
<video id="video1" height="120" width="160" autoplay muted></video>
<video id="video2" height="120" width="160" autoplay></video><br>
<input type="checkbox" onclick="mute()">mute</input><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
PeerConnections basically stop sending packets in this muted state, so it is highly efficient.
You should try using renegotiation, I believe the difference still exists how it is done in chrome and firefox:
In chrome, you just call addStream or removeStream on the PeerConnection object to add/ remove the stream, then create and exchange sdp.
In firefox, there is no direct removeStream, you need to use RTCRtpSender and addTrack and removeTrack methods, you can take a look at this question

Video displayed in ReactJS component not updating

I'm new to ReactJS (0.13.1), and I've created a component in my app to display HTML5 video.
It seems to work perfectly but only for the first selection. The video that is actually displayed and playing in the page doesn't change when you switch from one video to another (when this.props.video changes).
I can see the <source src='blah.mp4' /> elements update in the Chrome inspector but the actually rendered video in the page doesn't change and keeps playing if it was already. Same thing happens in Safari & Firefox. All the other elements update appropriately as well.
Any ideas?
Anyway my component below:
(function(){
var React = require('react');
var VideoView = React.createClass({
render: function(){
var video = this.props.video;
var title = video.title === ''? video.id : video.title;
var sourceNodes = video.media.map(function(media){
media = 'content/'+media;
return ( <source src={media} /> )
});
var downloadNodes = video.media.map(function(media){
var ext = media.split('.').slice(-1)[0].toUpperCase();
media = 'content/'+media;
return (<li><a className="greybutton" href={media}>{ext}</a></li>)
});
return (
<div className="video-container">
<video title={title} controls width="100%">
{sourceNodes}
</video>
<h3 className="video-title">{title}</h3>
<p>{video.description}</p>
<div className="linkbox">
<span>Downloads:</span>
<ul className="downloadlinks">
{downloadNodes}
</ul>
</div>
</div>
)
}
});
module.exports = VideoView;
})();
UPDATE:
To describe it another way:
I have a list of links with onClick handlers that set the props of the component.
When I click on a video link ("Video Foo") for the first time I get
<video title="Video Foo" controls>
<source src="video-foo.mp4"/>
<source src="video-foo.ogv"/>
</video>
and "Video Foo" appears and can be played.
Then when I click on the next one ("Video Bar") the DOM updates and I get
<video title="Video Bar" controls>
<source src="video-bar.mp4"/>
<source src="video-bar.ogv"/>
</video>
However it is still "Video Foo" that is visible and can be played.
It's like once the browser has loaded media for a <video> it ignores any changes to the <source> elements.
I have described some approaches for plain JavaScript here. Based on that I have found solutions for React which work for me:
using src attribute on video itself:
var Video = React.createComponent({
render() {
return <video src={this.props.videoUrl} />;
}
});
Dana's answer is a great option extending this solution.
using .load() call on video element:
var Video = React.createComponent({
componentDidUpdate(_prevProps, _prevState) {
React.findDOMNode(this.refs.video).load(); // you can add logic to check if sources have been changed
},
render() {
return (
<video ref="video">
{this.props.sources.map(function (srcUrl, index) {
return <source key={index} src={srcUrl} />;
})}
</video>
);
}
});
UPD:
of course it's possible to add unique key attribute for <video> tag (for example based on your sources), so when sources will change it will be changed as well. But it will cause <video> to be re-rendered completely and it may cause some UI flashes.
var Video = React.createComponent({
render() {
return (
<video key={this.props.videoId}>
{this.props.sources.map(function (srcUrl, index) {
return <source key={index} src={srcUrl} />;
})}
</video>
);
}
});
I faced the same issue and I didn't have access to the <video> HTML tag as I was using a library to render the video (not the native <video> HTML tag) which is internally responsible for rendering the <video> tag.
In this case I have found another solution which I think is better to solve the same issue.
Before:
<VideoLibrary src={this.props.src} />
After:
<React.Fragment key={this.props.src}>
<VideoLibrary src={this.props.src} />
</React.Fragment>
Or this if you're using the native <video> HTML tag:
<React.Fragment key={this.props.src}>
<video src={this.props.src} />
</React.Fragment>
This way React will render different video tags because the src prop will be different hence rendering a different HTML tag each time to avoid this issue.
I find this way cleaner and simpler and will work in both cases if you have or don't have access to the <video> HTML tag.
Found the answer
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach
https://html.spec.whatwg.org/multipage/embedded-content.html#the-source-element
It's a pretty hacky and fragile, but it got the job done for my cases.
(function(){
var React = require('react');
var VideoView = React.createClass({
pickSource: function(media){
var vid = document.createElement('video');
var maybes = media.filter(function(media){
var ext = media.split('.').slice(-1)[0].toUpperCase();
return (vid.canPlayType('video/'+ext) === 'maybe');
});
var probablies = media.filter(function(media){
var ext = media.split('.').slice(-1)[0].toUpperCase();
return (vid.canPlayType('video/'+ext) === 'probably');
});
var source = '';
if (maybes.length > 0) { source = maybes[0]; }
if (probablies.length > 0) { source = probablies[0]; }
source = (source === '')? '' : 'content/'+source;
return source;
},
render: function(){
var video = this.props.video;
var title = video.title === ''? video.id : video.title;
var src = this.pickSource(video.media);
var downloadNodes = video.media.map(function(media){
var ext = media.split('.').slice(-1)[0].toUpperCase();
media = 'content/'+media;
return (
<li><a className="greybutton" href={media}>{ext}</a></li>
)
});
return (
<div className="video-container">
<video title={title} src={src} controls width="100%"></video>
<h3 className="video-title">{title}</h3>
<p>{video.description}</p>
<div className="linkbox">
<span>Downloads:</span>
<ul className="downloadlinks">
{downloadNodes}
</ul>
</div>
</div>
)
}
});
module.exports = VideoView;
})();
Try this way
import React, { Component } from "react";
class Video extends Component<any, any> {
video: any = React.createRef();
componentDidUpdate(preProps: any) {
const { url } = this.props;
if (preProps && preProps.url && url) {
if (preProps.url !== url) {
this.video.current.src = url;
}
}
}
render() {
const { url } = this.props;
return (
<video controls ref={this.video}>
<source src={url} type="video/mp4" />
Your browser does not support HTML5 video.
</video>
);
}
}
I had the same problem with making a playlist with videos.
So I separated the video player to another react component
and that component received two props: contentId (video identify) & videoUrl (video URL).
Also I added a ref to the video tag so I can manage the tag.
var Video = React.createClass({
componentWillReceiveProps (nextProps) {
if (nextProps.contentId != this.props.contentId) {
this.refs['videoPlayer'].firstChild.src = this.props.videoUrl;
this.refs['videoPlayer'].load()
}
},
propType: {
contentId: React.PropTypes.string, // this is the id of the video so you can see if they equal, if not render the component with the new url
videoUrl: React.PropTypes.string, // the video url
} ,
getDefaultProps(){
return {
};
},
render() {
return (
<video ref="videoPlayer" id="video" width="752" height="423">
<source src={this.props.videoUrl} type="video/mp4" />
</video>
);
}
});
module.exports = Video;
this is much more clean:
<Video contentId="12" videoUrl="VIDEO_URL" />
Try to remove the source tag and instead have only the video tag and add src attribute to it like this example
<video src={video} className="lazy" loop autoPlay muted playsInline poster="" />
If you are getting the data from server and you want it to update the video link once you have new data.
import React, {Fragment, useEffect, useState} from "react";
const ChangeVID =(props)=> {
const [prevUploaded, setPrevUploaded] =useState(null);
useEffect(()=>{
if(props.changeIMG) {
setPrevUploaded(props.changeIMG)}
},[])
return(<Fragment>
{prevUploaded && <Suspense
fallback={<div>loading</div>}>
<div className="py-2" >
{ <video id={prevUploaded.duration} width="320" height="240" controls >
<source src={prevUploaded.url} type="video/mp4" />
</video>}
</div>
</Suspense>
}<);
}

Categories

Resources