I'm using react-player https://github.com/cookpete/react-player to play my videos. My problem is, how can I pause other videos while selected video is playing?
const videoRef = useRef();
const updateVideoHandler = async (videoId, videoTitle) => {
setSelectedVideoId(videoId);
if (!selectedVideoId) {
videoRef?.current?.player?.player?.onPause();
}
};
<ReactPlayer
ref={videoRef}
onPlay={() => updateVideoHandler(video.id, video.title)}
playsinline={true}
playing={true}
controls={true}
url={video?.url}
width="100%"
height="100%"
playIcon={
<div
className="play-icon"
role="button"
tabIndex={0}
style={{ outline: "none" }}
>
{" "}
<img src="/images/play.png" alt="" />
</div>
}
light={video?.pic}
/>;
You could store all player instances in a Context and use a Provider and Consumer to pause all players if one starts playing.
Since you pass a playing boolean to ReactPlayer, you can easily store a id or reference of the current playing player.
For example:
PlayerProvider.jsx
export const PlayerContext = React.createContext({
play: (playerId) => true,
pause: (playerId) => true,
isPlaying: (playerId) => false,
});
function PlayerProvider({ children }) {
// store the id of the current playing player
const [playing, setPlaying] = useState('');
// set playing to the given id
const play = playerId => setPlaying(playerId);
// unset the playing player
const pause = () => setPlaying(false);
// returns true if the given playerId is playing
const isPlaying = playerId => playerId === playing;
return (
<PlayerContext.Provider value={{ play, pause, isPlaying }}>
{children}
</PlayerContext.Provider>
)
}
export default PlayerProvider;
Player.jsx
import { PlayerContext } from './PlayerProvider';
function Player({ video, id }) {
const { isPlaying, play, pause } = useContext(PlayerContext);
<ReactPlayer
ref={videoRef}
playsinline={true}
playing={isPlaying(id)}
controls={true}
url={video?.url}
width="100%"
height="100%"
onPause={() => pause(id)}
onEnded={() => pause(id)}
onClickPreview={() => play(id)}
playIcon={
<div
className="play-icon"
role="button"
tabIndex={0}
style={{ outline: "none" }}
>
{" "}
<img src="/images/play.png" alt="" />
</div>
}
light={video?.pic}
/>;
}
export default Player;
Page.jsx
import PlayerProvider from './PlayerProvider';
import Player from './Player';
function Page() {
return (
<PlayerProvider>
<Player video="/path/to/video1.mp4" id="player1" />
<Player video="/path/to/video2.mp4" id="player2" />
<Player video="/path/to/video3.mp4" id="player3" />
</PlayerProvider>
)
}
Actially this is very easy process to get
try it out
export const VideoPlayer = () =>{
const videoooo = useRef();
const pauseVideo = () => {
//at the place of pauseVideo you can use "stopVideo", "playVideo"
videoooo.current.contentWindow.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
"*"
);
};
return(<> <iframe
ref={videoooo}
id="myVideoId"
src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"
></iframe>
<button
onClick={() => {
pauseVideo();
}}
>
Pause
</button></>)
}
it is very easy and useful syntax from js
// unset the playing player
const pause = () => setPlaying(false);
if you remove this line from the code it is working perfectly, when one video is already playing and you click on the second video, onPause is invoked and it is calling the pause function due to that setPlaying updating the playing value due to that page rerendering and in that time playing value is false and it does not match with any video id and that's why every video is stopped playing.
I implemented it using video-react here :
react-video-js
You need to use
controls,
preload='auto',
autoplay
Or
You can also pop-up a modal and show videos and use this
<div>
<button onClick={this.playVideo}>
Play!
</button>
<button onClick={this.pauseVideo}>
Pause!
</button>
</div>
where you need to store the states inside these onClick for play and pause depending upon the useref of a particular video else if you use a Modal then destroy it after close so that video doesn't play once you close.
Related
IM trying to create an audio player, with a master play and pause button, each song has its play and pause button but that can be override by the master play and pause.
const playing = () => {
if(isPlaying){
setIsPlaying(false)
masterPlay()
}else{
setIsPlaying(true)
handlePlay()
}
};
const handlePlay = (song) =\> {
setCurrentTrack(song);
setIsPlaying(true);
};
const masterPlay = () => {
handlePlay()
setIsPlaying(true);
console.log(isPlaying)
}
{!isPlaying ? (
//if playing is false, play the audio
<PlayArrowIcon onClick = {masterPlay} /\>
) : (
//else pause the audio
<PauseIcon onClick = {handlePause} /\>
)}
<button className="next_button" onClick={() => handlePrevious}>
<SkipPreviousIcon />
</button>
<ul>
{songs.map((song) => {
return (
<li key={song.id}>
{song.track_name}
<PlayArrowIcon onClick={() => handlePlay(song)} />
<button onClick={() => handlePlaylist(song)}>
create playlist
</button>
</li>
);
})}
</ul>
{currentTrack && (
<audio
ref={audioRef}
src={currentTrack.track_url}
onPlay={playing}
onPause={()=>handlePause}
onEnded={handleEnded}
onTimeUpdate={handleTimeUpdate}
autoPlay={isPlaying}
/>
)}
</div>
`
I'm having difficulty passing the current track into the master play, without ,mapping the songs array how can I make the master play control the music
I was creating this React component and I was astonished by the fact that when I clicked on the video I got false on console immediatelly after the video started. I was expecting that it would print true when the video started, and false when it finished. I think I'm confusing the lifecycle of this particular component, and I would be really grateful if someone could clarify this to me.
const Video = ({src, type, index, isAutoPlay}) => {
const [play, setPlay] = useState(isAutoPlay)
const playRef = useRef();
useEffect(() => {
if (play && playRef.current) {
playRef.current.play();
}
return () => setPlay(false)
}, [play]);
return (
<>
<video
className="slide"
ref={playRef}
onClick={() => {
setPlay(true);
console.log(play);}}>
<source src={src} type={type} key={index}/>
Your browser does not support the video tag.
</video>
</>
)
}
I am building a simple music player but where I fail is at trying to execute one item from the array at a time. I am using React H5 Audio Player package to play the music. I am currently mapping through all the songs but I don't know how to properly play one at a time. I appreciate any help. I've been stuck on this for a few days.
import { SongContext } from '../../SongContext';
import AudioPlayer from 'react-h5-audio-player';
import 'react-h5-audio-player/lib/styles.css';
import './Player.css';
const Player = () => {
const { songs } = useContext(SongContext);
return (
<>
{songs.length > 0 &&
songs.map((song) => (
<div className="player" key={song.id}>
<AudioPlayer
// autoPlay
// src={song.preview}
showJumpControls={false}
customVolumeControls={[]}
customAdditionalControls={[]}
onPlay={() => console.log('playing')}
/>
</div>
))}
</>
);
};
export default Player;
Don't map all the songs at once, take a song by index (currentSong), and when it's done, use the onEnded event to increment the index, so the next one would play.
Example (codepen):
const Player = () => {
const { songs } = useContext(SongContext);
const [currentSong, setCurrentSong] = useState(0);
const song = songs[currentSong];
if(!song) return null; // don't render the player when no song is available
return (
<div className="player">
<AudioPlayer
autoPlay
src={song.preview}
showJumpControls={false}
customVolumeControls={[]}
customAdditionalControls={[]}
onPlay={() => console.log('playing')}
onEnded={() => setCurrentSong(i => i + 1)}
/>
</div>
);
};
I'd like certain elements on my site to emit a sound when clicked. I easily did that by adding an audio element with a ref, and a function that plays the refs sound onClick.
const sound = require('../sounds/bird.mp3');
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <div>
<audio ref={soundRef}><source src={sound} /></audio>
<img src="bird.png" onClick={playSound} />
</div>
Since I now found out I may need to reuse this, I decided to create an Audio component to encapsulate the clicked element. I'd like it to receive the sound's file name as a property:
<Audio soundName="bird">
<div><img src="bird.png" /></div>
</Audio>
My problem is: in the Audio component, I get the soundName and children props and render the {children, but how do I add an onClick even to the child element, so it would trigger the Audio element playSound function?
What I currently have in the Audio component:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
{children} // <--- this is where I need to somehow add the event
</>
}
I'm hoping I'm missing a tiny thing here...
You can wrap your children with something, like a div, who can listen for your event, something like:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
<div onClick={ playSound }>
{children} // <--- this is where I need to somehow add the event
</div>
</>
}
I think this covers most of your cases.
There might be a children which intercept the event before the Audio component and prevent the event propagation to the parent, something like:
<Audio soundName="bird">
<img
src="bird.png"
onClick={ event => {
doSomethingOnThisImageClick()
event.stopPropagation()
}}
/>
</Audio>
If you know that this case might happen but you still want to play the file no matter what, you need to recognize the event in its capture phase, BEFORE the child component even know it, using the Capture variant of the event name, like:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
{ /* notice here? */ }
{ /* | */ }
{ /* v */ }
<div onClickCapture={ playSound }>
{children}
</div>
</>
}
I am attempting to have the next video in a channel play right after the other. Currently, the website has the videos showing one after the other, but my goal is to show one video and the second one plays right after the other is done. I have the function set up for the video ending, but right now it just causes an alert. I am using the Youtube Data API to pull in the videos and their information.
Here is a snippet of the code I am using:
constructor() {
super();
this.state = {
videos: [],
};
}
componentDidMount() {
fetch('https://www.googleapis.com/youtube/v3/search?key='APIKey'&channelId=UCXIJgqnII2ZOINSWNOGFThA&part=snippet,id&order=date&maxResults=2')
.then(results => {
return results.json();
}).then(data => {
let videos = data.items.map((videos) => {
return(
<div key={videos.items}>
<YouTube
className="player"
id="video"
videoId={videos.id.videoId}
opts={VIDEO_OPTS}
onEnd={this.playNextVideo}
/>
<h2>{videos.snippet.title}</h2>
<p className="channel">Video by: {videos.snippet.channelTitle}</p>
</div>
);
});
this.setState({videos: videos});
console.log("state", this.state.videos);
})
}
playNextVideo = () => {
alert('The video is done!');
}
I suggest you to do few things a little bit different.
First save the results.json(); to your videos variable in the state and not the whole youtube component, that's bad practice.
Second save another variable in your state that indicates the current playing video id (playingVideoId). Initialize it in the componentDidMount and change it in your playNextVideo function like this:
constructor() {
super();
this.index=0;
}
componentDidMount() {
fetch('https://www.googleapis.com/youtube/v3/search?key='APIKey'&channelId=UCXIJgqnII2ZOINSWNOGFThA&part=snippet,id&order=date&maxResults=2').then(results => {
this.setState({videos: results.json()});
this.setState({playingVideoId: this.state.videos[this.index]});
})}
playNextVideo = () => {
this.setState({playingVideoId: this.state.videos[++this.index]});
}
Now use the render function to render the component
render() {
return(
<YouTube
className="player"
id="video"
videoId={this.state.playingVideoId}
opts={VIDEO_OPTS}
onEnd={this.playNextVideo}
/>
);
}