I have a component AllRow. Inside of AllRow, I reuse the Row component two times. Inside the Row component there are poster of movies and when i click on them i can watch there trailers. I want that if I play a video from first Row the other video (if playing) from the second Row stop automatically. How can I achieve this?
This is my code.
import React from "react";
import Row from "../Components/Row.js";
function AllRows() {
return (
<div>
<Row/>
<Row/>
</div>
);
}
export default AllRows;
The Row component is
import React, { useState, useEffect } from "react";
import "../Styling/row.css";
import YouTube from "react-youtube";
import axios from "../Module/axios.js";
function Row() {
const base_url = "https://image.tmdb.org/t/p/w500/";
const [movies, setMovies] = useState([]);
const [trailerUrl, setTrailerUrl] = useState("");
useEffect(() => {
async function fetchData() {
const request = await axios.get(fetchURL);
setMovies(request.data.results);
return request;
}
fetchData();
}, [fetchURL]);
const opts = {
height: "390",
width: "100%",
playerVars: {
autoplay: 1,
},
};
const handleClick = (movie) => {
if (trailerUrl) {
setTrailerUrl("");
} else {
movieTrailer(movie?.name || movie?.title || "")
.then((url) => {
const urlParams = new URLSearchParams(new URL(url).search);
setTrailerUrl(urlParams.get("v"));
})
.catch((error) => console.log(error));
}
};
return (
<div>
<div>
{movies.map((movie) => (
<img
src="poster image source source"
key={movie.id}
alt={movie.title}
onClick={() => handleClick(movie)}
/>
))}
</div>
{trailerUrl && (
<YouTube className="row__video" videoId={trailerUrl} opts={opts} />
)}
</div>
);
}
export default Row;
I'm fetching data from tmdb API. I have tried many things but couldn't find any solution. Any help will be appreciated. Thanks :)
You can keep the state of the playing video in the AllRow component.
import React, { useEffect } from 'react';
import Row from '../Components/Row.js';
function AllRows() {
// To keep a track of the playing trailer amongst all the rows
const [playingTrailer, setPlayingTrailer] = useState(null);
return (
<div>
<Row playingTrailer={playingTrailer} setPlayingTrailer={setPlayingTrailer} />
<Row playingTrailer={playingTrailer} setPlayingTrailer={setPlayingTrailer} />
</div>
);
}
function Row({playingTrailer, setPlayingTrailer}) {
const base_url = 'https://image.tmdb.org/t/p/w500/';
const [movies, setMovies] = useState([]);
const [trailerUrl, setTrailerUrl] = useState('');
// to keep track of the video
const videoRef = null
useEffect(() => {
async function fetchData() {
const request = await axios.get(fetchURL);
setMovies(request.data.results);
return request;
}
fetchData();
}, [fetchURL]);
/**
* If playingTrailer changes and the displayed trailer in this <Row> is different from playingTrailer stop the video player
*/
useEffect(() => {
if(trailerUrl !== playingTrailer && videoPlayerRef !== null){
videoPlayerRef.pauseVideo()
}
},[playingTrailer])
const opts = {
height: '390',
width: '100%',
playerVars: {
autoplay: 1,
},
};
const handleClick = (movie) => {
if (trailerUrl) {
setTrailerUrl('');
} else {
movieTrailer(movie?.name || movie?.title || '')
.then((url) => {
const urlParams = new URLSearchParams(new URL(url).search);
setTrailerUrl(urlParams.get('v'));
})
.catch((error) => console.log(error));
}
};
/**
* use when the video playing, set the playing trailer in AllRows
* #param {*} event
*/
const onPlay= (event) => {
setPlayingTrailer(trailerUrl)
}
/**
* When video is ready, keep a ref on the player (maybe there's a better option to keep the video ref...)
* #param {*} event
*/
const onReady = (event) => {
videoRef = event.target
};
return (
<div>
<div>
{movies.map((movie) => (
<img
src="poster image source source"
key={movie.id}
alt={movie.title}
onClick={() => handleClick(movie)}
/>
))}
</div>
{trailerUrl && (
<YouTube
className="row__video"
videoId={trailerUrl}
opts={opts}
onReady={onReady}
onPlay={onPlay}
/>
)}
</div>
);
}
I'm trying to configure video.js in a next.js project but it doesn't work.
At the beginning of loading the player appears black and disappears suddenly.
In the console there is a warning saying the following:
"video.es.js?31bb:228 VIDEOJS: WARN: The supplied element is not included in the DOM"
The player component code is as follows:
import React from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
export const ThorPlayer = (props) => {
const videoRef = React.useRef(null);
const playerRef = React.useRef(null);
const {options, onReady} = props;
React.useEffect(() => {
// Make sure Video.js player is only initialized once
if (!playerRef.current) {
const videoElement = videoRef.current;
if (!videoElement) return;
const player = playerRef.current = videojs(videoElement, options, () => {
player.log('player is ready');
onReady && onReady(player);
});
// You can update player in the `else` block here, for example:
} else {
player.autoplay(options.autoplay);
player.src(options.sources);
}
}, [options, videoRef]);
// Dispose the Video.js player when the functional component unmounts
React.useEffect(() => {
const player = playerRef.current;
return () => {
if (player) {
player.dispose();
playerRef.current = null;
}
};
}, [playerRef]);
return (
<div data-vjs-player>
<video ref={videoRef} className='video-js vjs-big-play-centered' style={{ width: "800px", height:"400px" }}/>
</div>
);
}
export default ThorPlayer;
And the page that implements the component is this:
import React from 'react'
import ThorPlayer from '../../components/_ThorPlayer'
export default function index() {
const playerRef = React.useRef(null);
const videoJsOptions = {
autoplay: true,
controls: true,
responsive: true,
fluid: true,
sources: [{
src: 'https://obj-gravscale.zadarazios.com:443/v1/AUTH_f57eb386f52e4dc0bcdf19764aecc205/ct/bl_se.mp4',
type: 'video/mp4'
}]
};
const handlePlayerReady = (player) => {
playerRef.current = player;
// You can handle player events here, for example:
player.on('waiting', () => {
player.log('player is waiting');
});
player.on('dispose', () => {
player.log('player will dispose');
});
};
return (
<>
<h1>Teste de Player: </h1>
<ThorPlayer options={videoJsOptions} onReady={handlePlayerReady} />
<div></div>
</>
)
}
Could someone who has already implemented video.js in next.js help me with this problem?
Are you using React 18 by any chance? I was running into the same problem as you and it was caused by the fact that useEffect fires twice in development mode.
As a workaround until video.js 7.20 is released, you can use the technique described in this comment.
I have a hook that plays a provided audio file the first time it's clicked, and then every other time (false, true, false). I'd like it to play every time it's clicked regardless if it's the 1st time or 15th time. I've been trying different approaches, but so far I'm struggling to think of a clean solution to get this to work.
Any ideas how I can set the audio to start over each time it's clicked?
import React, { useState, useEffect } from 'react';
export const useAudio = (url) => {
const [audio, setAudio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => {
setPlaying(!playing);
};
// ! file might not be cleaning up
useEffect(() => {
setAudio(new Audio(url));
setPlaying(false);
}, [url]);
useEffect(() => {
playing ? audio.play() : audio.pause();
}, [playing]);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, [url]);
return [playing, toggle];
};
Try setting up the currentTime property of the audio object to 0. So, it will seek back to the 0th second. Then try again.
Syntax:
audio.currentTime = 0
In your code, you can try:
useEffect(() => {
audio.currentTime = 0
playing ? audio.play() : audio.pause();
}, [playing]);
I'm trying make a soundboard using React. I've pulled some code from other stack overflow answers but what I can't get to work is to have the audio restart when triggered again during playback. Instead it just continues to play to the end.
Here is my current code:
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'
const Button = (props) => {
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggleSound = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing]
);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, []);
return [playing, toggleSound];
};
useEffect(() => {
function handleClick(e) {
if(e.key === props.trigger){
toggleSound();
}
}
window.addEventListener('keydown', handleClick);
return () => {
window.removeEventListener('keydown', handleClick);
};
}, []);
const [playing, toggleSound] = useAudio(`./sounds/${props.audio}`);
return (
<ButtonWrapper playing={playing} onClick={toggleSound}>
{props.children} - {props.trigger.toUpperCase()}
</ButtonWrapper>
)
}
export default Button;
const ButtonWrapper = styled.button`
background: ${props => props.playing ? 'red' : 'white'};
border: none;
font-size: 20px;
`
Did you try to use .load() method?
The reference says that .load() reloads the element https://www.w3schools.com/tags/av_met_load.asp
import React, { Component } from 'react'
import { Button, Input, Icon,Dropdown,Card} from 'semantic-ui-react'
import { Link } from 'react-router-dom'
import $ from 'jquery'
import styles from './Home.scss'
import Modal from './Modal.jsx'
import MakeChannelModal from './MakeChannelModal.jsx'
class Music extends React.Component {
constructor(props) {
super(props);
this.state = {
play: false,
pause: true
};
this.url = "http://streaming.tdiradio.com:8000/house.mp3";
this.audio = new Audio(this.url);
}
play(){
this.setState({
play: true,
pause: false
});
console.log(this.audio);
this.audio.play();
}
pause(){
this.setState({ play: false, pause: true });
this.audio.pause();
}
render() {
return (
<div>
<button onClick={this.play}>Play</button>
<button onClick={this.pause}>Pause</button>
</div>
);
}
}
export default Music
This is the code that I am using to play the sound with url (this.url) in my react app. When I press the play button, it gives me an error
Uncaught TypeError: Cannot read property 'setState' of undefined
I am not sure why this is happpening since I don't see any undefined states. A;; states have been declared.
I am new to react so I might be missing something very important.
Please help!
ES6 class properties syntax
class Music extends React.Component {
state = {
play: false
}
audio = new Audio(this.props.url)
componentDidMount() {
audio.addEventListener('ended', () => this.setState({ play: false }));
}
componentWillUnmount() {
audio.removeEventListener('ended', () => this.setState({ play: false }));
}
togglePlay = () => {
this.setState({ play: !this.state.play }, () => {
this.state.play ? this.audio.play() : this.audio.pause();
});
}
render() {
return (
<div>
<button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
</div>
);
}
}
export default Music;
Hooks version (React 16.8+):
import React, { useState, useEffect } from "react";
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing]
);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, []);
return [playing, toggle];
};
const Player = ({ url }) => {
const [playing, toggle] = useAudio(url);
return (
<div>
<button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
</div>
);
};
export default Player;
Update 03/16/2020: Multiple concurrent players
In response to #Cold_Class's comment:
Unfortunately if I use multiple of these components the music from the other components doesn't stop playing whenever I start another component playing - any suggestions on an easy solution for this problem?
Unfortunately, there is no straightforward solution using the exact codebase we used to implement a single Player component. The reason is that you somehow have to hoist up single player states to a MultiPlayer parent component in order for the toggle function to be able to pause other Players than the one you directly interacted with.
One solution is to modify the hook itself to manage multiple audio sources concurrently. Here is an example implementation:
import React, { useState, useEffect } from 'react'
const useMultiAudio = urls => {
const [sources] = useState(
urls.map(url => {
return {
url,
audio: new Audio(url),
}
}),
)
const [players, setPlayers] = useState(
urls.map(url => {
return {
url,
playing: false,
}
}),
)
const toggle = targetIndex => () => {
const newPlayers = [...players]
const currentIndex = players.findIndex(p => p.playing === true)
if (currentIndex !== -1 && currentIndex !== targetIndex) {
newPlayers[currentIndex].playing = false
newPlayers[targetIndex].playing = true
} else if (currentIndex !== -1) {
newPlayers[targetIndex].playing = false
} else {
newPlayers[targetIndex].playing = true
}
setPlayers(newPlayers)
}
useEffect(() => {
sources.forEach((source, i) => {
players[i].playing ? source.audio.play() : source.audio.pause()
})
}, [sources, players])
useEffect(() => {
sources.forEach((source, i) => {
source.audio.addEventListener('ended', () => {
const newPlayers = [...players]
newPlayers[i].playing = false
setPlayers(newPlayers)
})
})
return () => {
sources.forEach((source, i) => {
source.audio.removeEventListener('ended', () => {
const newPlayers = [...players]
newPlayers[i].playing = false
setPlayers(newPlayers)
})
})
}
}, [])
return [players, toggle]
}
const MultiPlayer = ({ urls }) => {
const [players, toggle] = useMultiAudio(urls)
return (
<div>
{players.map((player, i) => (
<Player key={i} player={player} toggle={toggle(i)} />
))}
</div>
)
}
const Player = ({ player, toggle }) => (
<div>
<p>Stream URL: {player.url}</p>
<button onClick={toggle}>{player.playing ? 'Pause' : 'Play'}</button>
</div>
)
export default MultiPlayer
Example App.js using the MultiPlayer component:
import React from 'react'
import './App.css'
import MultiPlayer from './MultiPlayer'
function App() {
return (
<div className="App">
<MultiPlayer
urls={[
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
]}
/>
</div>
)
}
export default App
The idea is to manage 2 parallel arrays:
your audio sources (built from the urls props you pass to the parent component ; the urls props is an array of strings (your MP3 URLs))
an array tracking the state of each player
The toggle method updates the player state array based on the following logic:
if there is a player currently active (i.e. audio is playing) and this active player is not the player targeted by the toggle method, revert that player's playing state to false, and set the targeted player's playing state to true [you clicked on 'play' while another audio stream was already playing]
if the player currently active is the player targeted by the toggle method, simply revert the targeted player's playing state to false [you clicked on 'pause']
if there is no player currently active, simply set the targeted player's state to true [you clicked on 'play' while no audio stream was currently playing]
Note that the toggle method is curried to accept the source player's index (i.e. the index of the child component where the corresponding button was clicked).
Actual audio object control happens in useEffect as in the original hook, but is slightly more complex as we have to iterate through the entire array of audio objects with every update.
Similarly, event listeners for audio stream 'ended' events are handled in a second useEffect as in the original hook, but updated to deal with an array of audio objects rather than a single such object.
Finally, the new hook is called from the parent MultiPlayer component (holding multiple players), which then maps to individual Players using (a) an object that contains the player's current state and its source streaming URL and (b) the toggle method curried with the player's index.
CodeSandbox demo
You can also accomplish this by using the useSound hook.
To do this, first install the npm package:
npm install use-sound
Imports:
import useSound from 'use-sound'
import mySound from '../assets/sounds/yourSound.mp3' // Your sound file path here
Usage example 1
A simple approach..
function MyButton(){
const [playSound] = useSound(mySound)
return (
<button onClick={() => playSound()}>
Play Sound
</button>
)
}
Usage example 2
In this setup we can control the volume. Also, playSound() will be called inside the handleClick() function, allowing you to do more things on click than just playing a sound.
function MyButton(){
const [playSound] = useSound(mySound, { volume: 0.7 }) // 70% of the original volume
const handleClick = () => {
playSound()
// maybe you want to add other things here?
}
return (
<button onClick={() => handleClick()}>
Play Sound
</button>
)
}
For more info click here or here
I faced a different problem with this implementation of the answer.
It seemed the browser was continuously trying to download the sound on every re-render.
I ended up using useMemo for the Audio with no dependencies which causes the hook to only ever once create the Audio and never attempt to recreate it.
import {useMemo, useEffect, useState} from "react";
const useAudio = url => {
const audio = useMemo(() => new Audio(url), []);
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing]
);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, []);
return [playing, toggle];
};
export default useAudio;
I got some problems following these steps when working with Next Js because Audio is HTMLElement tag, eventually, it was rendering me a big fat error, so I decided to study more and the result for it in my project was the following:
//inside your component function.
const [audio] = useState( typeof Audio !== "undefined" && new Audio("your-url.mp3")); //this will prevent rendering errors on NextJS since NodeJs doesn't recognise HTML tags neither its libs.
const [isPlaying, setIsPlaying] = useState(false);
To handle the player, I made a useEffect:
useEffect(() => {
isPlaying ? audio.play() : audio.pause();
}, [isPlaying]);
You will manage the state "isPlaying" according to the functions you make so far.
I'm a bit late to the party here but piggy backing off of 'Thomas Hennes':
One problem people looking at this will run into is, if you try to use this code verbatim in an app with multiple pages, they are not going to have a nice time. Since state is managed at the component, you can play, navigate and play again.
To get around that you want to have your component push it's state up to App.js instead and manage the state there.
Allow me to show what I mean.
My player component looks like this:
import React, { Component } from 'react'
class MusicPlayer extends Component {
render() {
const { playing } = this.props.player;
return (
<div>
<button onClick={this.props.toggleMusic.bind(this, playing)}>{playing ? "Pause" : "Play"}</button>
</div>
);
}
};
export default MusicPlayer;
Then in my App.js it looks something like this (using a TODO list sample app):
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import './App.css';
import Header from './componets/layout/Header'
import Todos from './componets/Todos'
import AddTodo from './componets/AddTodo'
import About from './componets/pages/About'
import MusicPlayer from './componets/MusicPlayer'
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = { playing: false, todos: [] }
this.audio = new Audio('<YOUR MP3 LINK HERE>');
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/todos')
.then(res => this.setState({ playing: this.state.playing, todos: res.data }))
}
toggleComplete = (id) => {
this.setState({ playing: this.state.playing, todos: this.state.todos.map(todo => {
if (todo.id === id){
todo.completed = !todo.completed
}
return todo
}) });
}
delTodo = (id) => {
axios.delete(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(res => this.setState({ playing: this.state.playing, todos: [...this.state.todos.filter(todo => todo.id !== id)] }));
}
addTodo = (title) => {
axios.post('https://jsonplaceholder.typicode.com/todos', {
title,
completed: false
})
.then(res => this.setState({ playing: this.state.playing, todos: [...this.state.todos, res.data]}))
}
toggleMusic = () => {
this.setState({ playing: !this.state.playing, todos: this.state.todos}, () => {
this.state.playing ? this.audio.play() : this.audio.pause();
});
}
render() {
return (
<Router>
<div className="App">
<div className="container">
<Header />
<Route exact path="/" render={props => (
<React.Fragment>
<AddTodo addTodo={this.addTodo} />
<Todos todos={this.state.todos} toggleComplete={this.toggleComplete} delTodo={this.delTodo} />
</React.Fragment>
)} />
<Route path="/About" render={props => (
<React.Fragment>
<About />
<MusicPlayer player={this.state} toggleMusic={this.toggleMusic} />
</React.Fragment>
)} />
</div>
</div>
</Router>
);
}
}
export default App;
Uncaught TypeError: Cannot read property 'setState' of undefined
The error occurs because of how the this keyword works in JavaScript. I think the Audio should play just fine if we solve that issue.
If you do a console.log(this) inside play() you will see that this it is undefined and that's why it throws that error, since you are doing this.setState().Basically the value of this inside play() depends upon how that function is invoked.
There are two common solutions with React:
Using bind() to set the value of a function's this regardless of how it's called:
constructor(props) {
super(props);
this.play() = this.play.bind(this);
}
Using arrow functions which don't provide their own this binding
<button onClick={() => {this.play()}}>Play</button>
Now you will have access to this.setState and this.audio inside play(), and the same goes for pause().
You can try this, it work on me
var tinung = `${window.location.origin}/terimakasih.ogg`;
var audio = document.createElement("audio");
audio.autoplay = true;
audio.load();
audio.addEventListener(
"load",
function() {
audio.play();
},
true
);
audio.src = tinung;