ReactPlayer make 2 file play in same time - javascript

I want to play 2 file in reactjs use ReactPlayer , file 1 is video music include audio human voice , file 2 is music only but the human voice has been deleted.
The problem when I run the code below is file 1 may start sooner than file 2 or vice versa , my question is can I play 2 file together , so when file 1 loading or render , file 2 will do same as file 1
This the code
import React, { useState } from "react";
import ReactPlayer from "react-player";
function App(){
const [playing, setPlaying] = useState(true);
const [muted, setMuted] = useState(true);
function handlePlayPause() {
setPlaying(!playing);
}
function handleMuted() {
setMuted(!muted);
}
return(
<div>
//play video music "I can fly include the music with human vocal"
<ReactPlayer
playing={playing}
url={"I can Fly.mp4"}
muted={muted}
/>
//play music only "I can fly (the file no human vocal)"
<ReactPlayer
playing={playing}
url={"I can fly(no vocal).mp3"}
muted={!muted}
hidden
/>
<button onClick={() => handlePlayPause()}>
{playing ? "pause" : "play"}
</button>
<button onClick={() => handleMuted()}>
{muted ? "vocal" : "no vocal"}
</button>
</div>
)}
export default App;
Hope you guys understand what I'm asking , sorry for my bad English :D

I guess the issue is from a video needs time to get ready before playing. Each video has a different its own time which means each video would have a different time to start playing.
As a result of that, we have to wait until all videos ready before playing them all at once. Luckily, react-player has offered a onReady callback telling that video is ready to play. Here is the general idea for you:
import React from "react";
import ReactPlayer from "react-player";
// Assuming to have 2 videos
const links = [
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
];
export default function App() {
// Count number of videos ready to play
const [readyCount, setReadyCount] = React.useState(0);
const [playing, setPlaying] = React.useState(false);
// Just keep counting as a video ready
const onReady = () => {
setReadyCount(readyCount + 1);
};
React.useEffect(() => {
// All videos ready to play, get them played
if (readyCount === links.length) {
setPlaying(true);
}
}, [readyCount]);
return (
<div className="App">
{links.map((url) => (
<ReactPlayer key={url} playing={playing} onReady={onReady} url={url} />
))}
</div>
);
}
I also have created a codesandbox for you: https://codesandbox.io/s/kind-bardeen-59t8f?file=/src/App.js

Related

Play local audio in React

I need to play local audio in React using hooks. Application will be deployed later to some server.
Application folder consists of the following:
index.html
index.css
index.js
audio folder with first.mp3 and second.mp3
It looks like this:
I have added screenshot because without CSS it wouldn't we clear what I need to accomplish. (just two simple numbers would be printed in div). Codepen link (with CSS)
So I should play sound when these Box components are clicked.
Here's 'index.js' file:
import React, { useState } from 'react';
import ReactDOM from 'react-dom'
import "./index.css"
const sounds = [
{
key: "1",
mp3: "./audio/first.mp3",
},
{
key: "2",
mp3: "./audio/second.mp3",
}
];
const App = () => {
const [keys, setKeys] = useState([
"1",
"2"
]);
return (
<div id="display" className="display">
{sounds.map((sound, id) => {
return <Box text={sound.key} audio={sound.mp3} />;
})}
</div>
);
};
const playSound=(props)=>{
return(
props.audio.current.play;
)
}
const Box = (props) => {
return (
<div className="box" onClick={playSound(props)}>
{props.text}
<audio src={props.audio} className="clip" id={props.text}/>
</div>
);
};
ReactDOM.render(<App/>, document.getElementById("root"));
Problem here is props.audio.current.play;. It doesn't play the sound.
I tried to console.log(props.audio) and it prints correctly for ex. ./audio/first.mp3
Could you please help me to fix this?
I can help you out by providing a general idea:
let audioEl = new Audio(audioUrl);
// Play
audioEl.play();
// Pause
audioEl.pause();
// Set current time
audioEl.currentTime = 0;

Preload images from an Array of paths, then pass it to a component thats gonna use it

so i am creating a simple game and i render it if someone presses a start button on the first render. i want to preload all the images that the component is gonna use, so that when you hit the start button its already preloaded.
this is how the array of image paths look like:
const imagesArr = [
"/src/images/cheetah-min.webp",
"/src/images/dolphin-min.webp",
"/src/images/gorilla-min.webp",
"/src/images/lion-min.webp",
"/src/images/tiger-min.webp",
"/src/images/troll-min.webp",
"/src/images/werewolf.webp",
"/src/images/wolf-min.webp"
]
This is my App.jsx:
function App() {
const [isPlaying, setIsPlaying] = useState(false);
return (
<div className="game-container">
{!isPlaying ? (
<div className="welcome-screen">
<h1 className="welcome-heading">Welcome to the game</h1>
<button
className="start-btn"
onClick={() => {
setTimeout(() => {
GAMESTARTS_SOUND.play();
setIsPlaying(true);
}, 3000);
}}
>
Play the game
</button>
</div>
) : (
<Game />
)}
</div>
);
}
as you can see there is this Game container that gets rendered if you press the play button. Inside that component im using the images. at the moment im just rendering them out using <img tags in the returned JSX from Game.jsx.
what I want is to preload the images before that component gets rendered? any ideas?

How to place an icon on an if then statement for a react button

I'm trying to create a button that will display a different icon and message when it is clicked. However, I'm unsure of how to include the icon inside the 'if then' statement within the < button > element. I'm quite new to React.
My code is below:
import React, { setState, useState, useEffect } from "react";
import { Pause,
Play } from 'react-feather';
function AudioPlayer() {
// use Audio constructor to create HTMLAudioElement
const audioTune = new Audio("<YOUR_AUDIO_FILE_PATH.mp3>");
// variable to play audio in loop
const [playInLoop, setPlayInLoop] = useState(false);
// variable to play audio in loop
const [isPlay, isPlaying] = useState(0);
// load audio file on component load
useEffect(() => {
audioTune.load();
}, []);
// play audio sound
const playSound = () => {
audioTune.play();
isPlaying(1);
};
// pause audio sound
const pauseSound = () => {
audioTune.pause();
};
// stop audio sound
const stopSound = () => {
audioTune.pause();
audioTune.currentTime = 0;
isPlaying(0);
};
const handlePlaying = () => {
if (isPlay) {
stopSound();
} else {
playSound();
}
};
return (
<div>
<div className="App">
<button onClick={handlePlaying}>
{isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
</button>
</div>
</div>
);
}
export default AudioPlayer;
I get an error here {isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
The error is:
SyntaxError
/src/components/Audio2.js: Unexpected token, expected ":" (57:30)
I've tried to insert the icon within the "" marks, but that is just displaying the button code as string.
Thanks for your help
You can do it like this
<button onClick={handlePlaying}>
{isPlay ? (
<>
<Pause /> Pause
</>
) : (
<>
<Play /> Listen to this page
</>
)}
</button>;

audio.play is not a function error from arrow function component using ref

I'm working on the freeCodeCamp drum machine project. When the user clicks the drum pad, I'd like a sound to play. Since the audio element isn't the real DOM element but a copy of it, to refer to it I need to use a ref (or at least I think that's why).
I followed the React doc instructions for using a ref in a function component, and I have a method handleClick that's triggered when you click a "drum pad" which I'd like to call audio.play(). However, when I click one of the drum pads, the app crashes with an error "audio.play is not a function." Is it a problem with the ref? Any suggestions appreciated.
Child component DrumPad.js:
const DrumPad = ({ id, letter, src }) => {
let audio = React.createRef(); // <--
const handleClick = () => { // <--
audio.play();
}
return (
<div
className="drum-pad"
id={id}
onClick={handleClick}
>
<p>{letter}</p>
<audio
ref={audio} // <--
id={letter}
src={src}
>
</audio>
</div>
);
}
Parent App.js:
const sounds = [
{ id: 'snare', letter: 'Q', src: 'https://www.myinstants.com/media/sounds/snare.mp3' },
// etc.
];
const App = () => {
return (
<div className="drum-machine">
<div className="drum-pads">
{sounds.map(sound => (
<DrumPad
id={sound.id}
letter={sound.letter}
src={sound.src}
/>
))}
</div>
</div>
);
}
The DOM node is actually store under the current key.
This should fix your problem:
const handleClick = () => {
audio.current.play();
}
React docs about createRef

How i play and pause React-gif image using ReactJS code

Long time I am tring to react-gif animate with play and pause.Like facebook gif image exactly.
I am using react-gif npm module.But does not working.Please anyone review my code.
coding.......
import Markdown from 'react-markdown';
import Gif from 'react-gif';
const linkRenderer = (linkNode) => {
return <a href={linkNode.href} title={linkNode.title} target="_blank" children={linkNode.children} />;
};
const imgixBase = 'https://chalees-min.imgix.net';
const imgixParameters = 'w=800&fit=max&auto=format,compress';
const imageRenderer = (imageNode) => {
const imageSource = imageNode.src.startsWith('/')
? `${imgixBase}${imageNode.src}?${imgixParameters}`
: imageNode.src;
return <Gif src={imageSource} alt={imageNode.alt} title={imageNode.title} />
};
const MarkdownCustomized = (props) => (
<Markdown
className={'markdown ' + (props.className || '')}
source={props.source || ''}
renderers={{
'Link': linkRenderer,
'Image': imageRenderer,
}} />
);
export default MarkdownCustomized;
You can't control (play-pause) an animated gif. Gifs in facebook are disguised videos.
There are some workarounds here, providing some kind of limited control.
I don't see any logic that makes the Gif component play or pause in your code.
Looking at the Gif react component code, I see two ways of making the Gif play and pause.
Set the prop playing to false to pause, and true to play. E.g Set gif to play
<Gif src={imageSource} alt={imageNode.alt} title={imageNode.title} playing={true} />
The Gif component has methods play and pause that can be accessed by using refs. So, on the component that uses Gif component, you can have something like the following:
class Parent extends Component {
handlePlayGif() {
this.currentGif.play();
}
handlePauseGif() {
this.currentGif.pause();
}
render() {
return ( //... rest of code
<Gif ref={(gif) => this.currentGif = gif} />
// ... rest of jsx
// onClick play gif
<div onClick={() => handlePlayGif()}>play gif</div>
);
}
}

Categories

Resources