Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- const [isPlaying, setIsPlaying] = useState(false);
- const [songPlayingIndex, setSongPlayingIndex] = useState(0);
- const song = songArr[songPlayingIndex];
- const [audio, setAudio] = useState(new window.Audio(song.url));
- class MusicControls extends Component{
- render() {
- const onClickPrevSong = () => {
- let newSongIndex = songPlayingIndex - 1;
- if (newSongIndex < 0) {
- newSongIndex = songArr.length - 1;
- }
- setSongPlayingIndex(newSongIndex);
- };
- const onClickNextSong = () => {
- let newSongIndex = songPlayingIndex + 1;
- if (newSongIndex >= songArr.length) {
- newSongIndex = 0;
- }
- setSongPlayingIndex(newSongIndex);
- };
- const onTogglePlaySong = () => {
- setIsPlaying(!isPlaying);
- };
- useEffect(() => {
- if (isPlaying) {
- audio.play();
- }
- if (!isPlaying) {
- audio.pause();
- }
- }, [isPlaying]);
- useEffect(() => {
- if (isPlaying) {
- audio.src = songArr[songPlayingIndex].url;
- audio.play();
- }
- }, [songPlayingIndex]);
- const onEndAudio = () => {
- onClickNextSong();
- };
- return (
- {onClickPrevSong, onEndAudio }
- );
- }
- }
- export default MusicControls;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement