1import React, { useState, useEffect } from "react";
2
3const useAudio = url => {
4 const [audio] = useState(new Audio(url));
5 const [playing, setPlaying] = useState(false);
6
7 const toggle = () => setPlaying(!playing);
8
9 useEffect(() => {
10 playing ? audio.play() : audio.pause();
11 },
12 [playing]
13 );
14
15 useEffect(() => {
16 audio.addEventListener('ended', () => setPlaying(false));
17 return () => {
18 audio.removeEventListener('ended', () => setPlaying(false));
19 };
20 }, []);
21
22 return [playing, toggle];
23};
24
25const Player = ({ url }) => {
26 const [playing, toggle] = useAudio(url);
27
28 return (
29 <div>
30 <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
31 </div>
32 );
33};
34
35export default Player;
1import ReactAudioPlayer from 'react-audio-player';
2//...
3<ReactAudioPlayer
4 src="my_audio_file.ogg"
5 autoPlay
6 controls
7/>
8
1class Music extends React.Component {
2 state = {
3 play: false
4 }
5 audio = new Audio(this.props.url)
6
7 componentDidMount() {
8 audio.addEventListener('ended', () => this.setState({ play: false }));
9 }
10
11 componentWillUnmount() {
12 audio.removeEventListener('ended', () => this.setState({ play: false }));
13 }
14
15 togglePlay = () => {
16 this.setState({ play: !this.state.play }, () => {
17 this.state.play ? this.audio.play() : this.audio.pause();
18 });
19 }
20
21 render() {
22 return (
23 <div>
24 <button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
25 </div>
26 );
27 }
28}
29
30export default Music;