I need some help on how I can update the DOM audio in real time.
I'm trying to make the audio muted and unmuted based on the user preference,
The recording is saved in the public folder.
The audio is working fine on the first load if you set mute to be true or false, then when you try to change it, the mute props do not update.
Here is a short sample of my code, I'm using next.js.
import { RECORDING } from '#/constants/media.constant';
import { useEffect, useState } from 'react';
function Sample() {
const [mute, setMute] = useState(false);
useEffect(() => {
(() => playWithAudio())();
}, []);
const playWithAudio = () => {
const tryToPlay = setInterval(() => {
// audio recording, format mp3
const audio = new Audio(RECORDING.HELLO);
audio.loop = true;
audio.muted = mute;
audio
.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(() => console.info('User has not interacted with DOM yet.'));
}, 1000);
};
return (
<>
<button onClick={() => setMute(!mute)}>Click</button>
</>
);
}
export default Sample;
Any help would be appreciated.
Give this a try
import { useEffect, useState } from "react";
import { RECORDING } from "#/constants/media.constant";
function Sample() {
const [mute, setMute] = useState(false);
const [audio, setAudio] = useState(null);
useEffect(() => {
setAudio(new Audio(RECORDING.HELLO));
}, []);
useEffect(() => {
if (audio) playWithAudio();
}, [audio]);
const playWithAudio = () => {
const tryToPlay = setInterval(() => {
// audio recording, format mp3
audio.loop = true;
audio.muted = mute;
audio
.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(() => console.info("User has not interacted with DOM yet."));
}, 1000);
};
return (
<>
<button
onClick={() => {
if (audio) audio.muted = !mute;
setMute(!mute);
}}
>
{mute ? "UnMute" : "Mute"}
</button>
</>
);
}
export default Sample;
I am attempting to show an image in a random position according to dynamic dimensions using a ref. However, when getting the useRef's current value, I recieve undefined likely because the useRef's target div hasn't loaded yet.
To overcome this, I am using a useEffect to wait for the target div to load.
However, when I run the program the image does not move because the useRef's current value remains at 0. The
import './MouseAim.css'
import '../Game.css'
import React, {useEffect, useRef, useState} from 'react'
import TargetImg from '../../../assets/Target.png'
import _ from "lodash";
function MouseAim() {
const [start, setStart] = useState(true)
const [target, setTarget] = useState(true)
const elementDimensions = useRef()
//wait for elementDimensions to be set
useEffect(() => {
console.log('elementDimensions', elementDimensions.current?.clientHeight)
} , [elementDimensions])
return (
<div>
<div className="main-container">
{
start ?
<div ref={elementDimensions} className="aim-container">
{
target ?
<input
className="target"
type="image"
style={{position: "relative", left:elementDimensions.current?.clientHeight+"px" , top:_.random(0, elementDimensions.current?.clientHeight)+"px"}}
onClick={() => console.log("hello")}
src={TargetImg}
alt="target"
/>
:null
}
</div>
:
<div className="start-container">
<input className="start-button" type="button" value="Start Game" onClick={() => setStart(true)}/>
</div>
}
</div>
</div>
)
}
export default MouseAim
Just set your target initial state to 'false', then set it to true when 'ref' is ready
Try this one:
const [start, setStart] = useState(true)
const [target, setTarget] = useState(false)
const elementDimensions = useRef()
//wait for elementDimensions to be set
useEffect(() => {
console.log('elementDimensions', elementDimensions.current?.clientHeight)
setTarget(true)
} , [elementDimensions])
Just like you mentioned, the useRef is set very initially when the div has not been mounted.
The div mounts when start becomes true. So that's where the trigger needs to happen.
Try to pass start as the dependency variables to the useEffect.
useEffect(() => {
console.log('elementDimensions', elementDimensions.current?.clientHeight)
} , [start, elementDimensions])
PS. If it doesn't work, pass target as the dependency variable as well.
useEffect(() => {
console.log('elementDimensions', elementDimensions.current?.clientHeight)
} , [start, target, elementDimensions])
I think separating your code into subcomponents will make this much simpler, as MouseAim has too much responsibility. In general, giving your components one clearly-defined purpose is a good way to simplify your codebase.
const AimContainer = () => {
const containerRef = useRef()
const [containerSize, setContainerSize] = useState();
useEffect(() => {
// set container size state here
}, [])
return <div ref={containerRef}>...</div>
}
const MouseAim = () => {
const [hasStarted, setHasStarted] = useState(false);
return <div>
{ hasStarted ?
<AimContainer />
:
<button onClick={() => setHasStarted(true)}>Start</button>
}
</div>
}
AimContainer will render before running useEffect, so you may also want to avoid rendering the target until containerSize is set.
I am creating a stopwatch in React.js and i am wondering why window.addEventListener('keydown', callback) re-render my component?
import { useEffect, useState } from 'react';
import './App.scss';
import Timer from './Timer';
import Button from './Button';
import Time from './Time';
const App = () => {
const [isRunning, setIsRunning] = useState(false);
const [start, setStart] = useState(new Time(0));
const [stop, setStop] = useState(new Time(0));
const handleStart = () => {
const now = new Date();
setIsRunning(true);
setStart(new Time(now));
setStop(new Time(now));
};
const handleStop = () => {
setIsRunning(false);
setStop(new Time(new Date()));
};
const getTime = () => {
if (isRunning) {
return new Time(new Date().getTime() - start.origin);
} else {
return new Time(stop.origin - start.origin);
}
};
const handleKeyDown = (key) => {
console.log(key.code === 'Space');
};
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
});
return (
<div className="stopwatch">
<Timer getTime={getTime} />
<div className="buttons">
<Button role={'start'} callback={handleStart} />
<Button role={'stop'} callback={handleStop} />
</div>
</div>
);
};
export default App;
When i click start and then stop after let's say 3s. <Timer /> show correctly time that has passed, but then when i press Space on keyboard <Timer /> is re-rendering, showing new time. Then, when i switch my web-browser to VSCode and again to web-browser, <Timer /> isn't re-rendering
Here is my Timer component
import { memo, useEffect, useRef } from 'react';
const Timer = ({ getTime }) => {
const timer = useRef();
console.log('timer rendered');
useEffect(() => {
function run() {
const time = getTime().formatted();
timer.current.textContent = `${time.m}:${time.s}.${time.ms}`;
requestAnimationFrame(run);
}
run();
return () => {
cancelAnimationFrame(run);
};
});
return <div ref={timer} className="timer"></div>;
};
export default memo(Timer);
no matter if I use [] in both or none of useEffect nothing changes.
As #davood-falahati says, adding an empty array as a second argument to useEffect would probably be desirable. From the docs:
... If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works. ...
In your use case:
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
I have a component in React that takes a URL and shows a button that lets the user stop/pause an audio file. This component is used multiple times on the page.
The button starts the audio just fine, however it audio.pause() does not stop the stream.
I am using Next.js, however I am importing the component like so:
const HistoryRow = dynamic(() => import('../components/HistoryRow'), { ssr: false });
Anyone know why this doesn't stop the stream? I can confirm it's entering the if statement just fine.
import { useState } from 'react';
import m from 'moment';
import path from 'path';
function HistoryRow({ data }) {
const [playing, setPlaying] = useState(false);
const audio = new Audio(`${window.location.origin}/audio-responses/${data.timestamp}.wav`);
audio.onended = function () {
setPlaying(false);
};
audio.onpause = function () {
setPlaying(false);
};
audio.onplay = function () {
setPlaying(true);
};
audio.onerror = function () {
setPlaying(false);
};
function execute() {
if (playing) {
audio.pause();
} else {
audio.play();
}
}
const stopSvg = (
<svg> /** svg data ** / </svg>
);
const playSvg = (
<svg> /** svg data ** / </svg>
);
return (
<div className="text-base flex leading-5 font-medium text-blue-600 truncate" onClick={() => execute()}>
{data.type === 'command' ? (playing ? stopSvg : playSvg) : null}
</div>
);
}
export default HistoryRow;
Whenever you state changes, the whole component is rerendered. This means that every variable in the component is rewritten. So you create an Audio instance, then start playing, the component rerenders and a new Audio instance is created en therefor you've lost the binding to the previous instance.
You can use the useRef hook to create a reference to the Audio instance that persists over the entire lifespan of the component. So it will never change unless you explicitly tell it to. You can access the instance with the current property on the returned useRef value.
Since React is state driven I would suggest using the useEffect hook to listen for changes in the playing state and either start or stop playing based on the value of the playing state, that's the other way around as you have it currently.
function HistoryRow({ data }) {
const [playing, setPlaying] = useState(false);
const [hasError, setHasError] = useState(false);
const audio = useRef(new Audio(`${window.location.origin}/audio-responses/${data.timestamp}.wav`));
audio.current.onended = function () {
setPlaying(false);
};
audio.current.onplay = function () {
setHasError(false);
};
const handleClick = () => {
setPlaying(playing => !playing);
});
useEffect(() => {
if (playing) {
audio.current.play().then(() => {
// Audio is playing.
}).catch(error => {
setHasError(true);
});
} else if (!hasError) {
audio.current.pause();
}
}, [playing, hasError]);
const stopSvg = (
<svg> /* svg data */ </svg>
);
const playSvg = (
<svg> /* svg data */ </svg>
);
return (
<div
className="text-base flex leading-5 font-medium text-blue-600 truncate"
onClick={handleClick}>
{data.type === 'command' ? (playing ? stopSvg : playSvg) : null}
</div>
);
}
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;