I added a musicplayer based on YouTube IFrame Player API for my personal site music page to play my playlist from YTmusic.
Stack
- React as a framework
- YouTube Data API v3 (fetching music list from youtube)
- react-youtube Youtube iframe player for react
react-youtube
Add player config.
import YouTube from 'react-youtube';
const opts = {
height: "250",
width: "350",
playerVars: {
autoplay: 1,
},
};
Add player from react-youtube.
<YouTube
videoId={"UEx5T0xfUk1td3F5ZFJ0elRhVHV6SGM3R0NYbEFSMmFPOC5EMEEwRUY5M0RDRTU3NDJC"} //Video id from youtube
opts={opts}
/>;
Create a control player event value
let videoElement: YouTubePlayer = null
Player event control like:pauseVideo()
, playVideo()
\
Example of video play button:
<button onClick={()=>videoElement.target.playVideo()}>
Play Video
</button>
PlayList
Create a API token on google api console, search and add YouTube Data API v3.
import React from 'react';
const [loading, setLoading] = React.useState(true);
const [playList ,setPlaylist] = React.useState(null);
React.useEffect(() => {
setLoading(true);
fetch(
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLyOL_RMmwqydRtzTaTuzHc7GCXlAR2aO8&key=<your_api_token>&maxResults=1000",
{}
)
.then((res) => res.json())
.then((data) => {
setPlaylist(data.items);
setLoading(false);
});
}, []);
return (
<ul>
{loading || !playList ? (
<h1>Loading...</h1>
) : (
playList.map((items) => <li key={items.id}>{items.snippet.title}</li>)
)}
</ul>
);
Source code: Github
Website: Personal site
⚡Thanks for reading, see you in the next blog.
Top comments (1)
the music songs is not working in mobile
can you fix it?