import React, { Component } from \'react\'
import { Button, Input, Icon,Dropdown,Card} from \'semantic-ui-react\'
import { Link } from \'react-router-dom\'
import $
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:
constructor(props) {
super(props);
this.play() = this.play.bind(this);
}
<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()
.
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;
I improved Jaxx's version slightly to include an eventListener
so that the button resets when the audio ends.
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:
urls
props you pass to the parent component ; the urls
props is an array of strings (your MP3 URLs))The toggle
method updates the player state array based on the following logic:
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 Player
s 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