'Music player playlist logic
I'm creating a small music player web app, everything works fine, I have a problem:
I want to create a playlist for it too and I'm kind of beginner in JS and I don't know how to create the logic for that (every time user click on a specific song title in playlist, play that exact song which he just clicked)I stored songs in a Array
Source code: https://yun.ir/qnrk56
Solution 1:[1]
You can implement this behaviour in different ways.
This is what I tried: https://jsfiddle.net/2qc0kwbg/
I added a function called setSong()
which accepts a parameter called number
and sets the song to that number (code logic copied from prevSong()
and nextSong()
). I added to every HTML element with the class .player__song
the onclick
attribute with the value of setSong(<index>)
where <index> is the index of the song in the array.
The setSong() function looks like this:
function setSong(number){
currentSong = number
showSong()
audio.play()
changeBgBody()
}
Solution 2:[2]
import React, { Component,useRef, setStatus, status } from 'react';
import ‘./Song.css';
import song1 from "./music/song1.mp3";
import song2 from "./music/song2.mp3"
import song3 from "./music/song3.mp3"
import song4 from "./music/song4.mp3"
export default function MusicPlayer() {
const data = [
{ imgSrc: ‘song1.png', audioSrc: song1},
{ imgSrc: ‘song2.png', audioSrc: song2},
{ imgSrc: ‘song3.png', audioSrc: song3},
{ imgSrc: ‘song4.png', audioSrc: song4},
];
return (
<div className=‘MusicPlayer>
<ol>
{data.map(({ imgSrc, audioSrc}) => (
<MediaComponent imgSrc={imgSrc} audioSrc={audioSrc} />
))}
</ol>
</div>
);
}
const MediaComponent = ({ imgSrc, audioSrc }) => {
const audioRef = useRef(null);
const toggleAudio = () =>
audioRef.current === null
? console.log("Audio component is not loaded yet.")
: audioRef.current.paused
? audioRef.current.play()
: audioRef.current.pause();
return (
<li>
<img src={imgSrc} onClick={toggleAudio} />
<audio
ref={audioRef}
src={audioSrc}
onLoad={() => setStatus({ ...status, isLoaded: true })}
onPlay={() => setStatus({ ...status, isPlaying: true })}
onPause={() => setStatus({ ...status, isPlaying: false })}
onError={() => setStatus({ ...status, error: true })}
/>
</li>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |