SHARE
TWEET

MusicControls.ts

zbeucler Jun 1st, 2020 1,430 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from 'react';
  2.  
  3.  
  4. const [isPlaying, setIsPlaying] = useState(false);
  5. const [songPlayingIndex, setSongPlayingIndex] = useState(0);
  6. const song = songArr[songPlayingIndex];
  7. const [audio, setAudio] = useState(new window.Audio(song.url));
  8.  
  9.  
  10.  
  11. class MusicControls extends Component{
  12.  
  13.  
  14.     render() {
  15.  
  16.  
  17.         const onClickPrevSong = () => {
  18.             let newSongIndex = songPlayingIndex - 1;
  19.             if (newSongIndex < 0) {
  20.               newSongIndex = songArr.length - 1;
  21.             }
  22.             setSongPlayingIndex(newSongIndex);
  23.           };
  24.           const onClickNextSong = () => {
  25.             let newSongIndex = songPlayingIndex + 1;
  26.             if (newSongIndex >= songArr.length) {
  27.               newSongIndex = 0;
  28.             }
  29.             setSongPlayingIndex(newSongIndex);
  30.           };
  31.           const onTogglePlaySong = () => {
  32.             setIsPlaying(!isPlaying);
  33.           };
  34.           useEffect(() => {
  35.             if (isPlaying) {
  36.               audio.play();
  37.             }
  38.             if (!isPlaying) {
  39.               audio.pause();
  40.             }
  41.           }, [isPlaying]);
  42.           useEffect(() => {
  43.             if (isPlaying) {
  44.               audio.src = songArr[songPlayingIndex].url;
  45.               audio.play();
  46.             }
  47.           }, [songPlayingIndex]);
  48.           const onEndAudio = () => {
  49.             onClickNextSong();
  50.           };
  51.  
  52.  
  53.         return (
  54.             {onClickPrevSong, onEndAudio }
  55.         );
  56.     }
  57. }
  58.  
  59. export default MusicControls;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top