DEV Community

Cover image for Build a music player with YouTube IFrame Player API
EliasChen
EliasChen

Posted on

Build a music player with YouTube IFrame Player API

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

Installation

Add player config.

import YouTube from 'react-youtube'; const opts = { height: "250", width: "350", playerVars: { autoplay: 1, }, }; 
Enter fullscreen mode Exit fullscreen mode

Add player from react-youtube.

<YouTube videoId={"UEx5T0xfUk1td3F5ZFJ0elRhVHV6SGM3R0NYbEFSMmFPOC5EMEEwRUY5M0RDRTU3NDJC"} //Video id from youtube opts={opts} />;  
Enter fullscreen mode Exit fullscreen mode

Create a control player event value

let videoElement: YouTubePlayer = null 
Enter fullscreen mode Exit fullscreen mode

Player event control like:pauseVideo(), playVideo()\
Example of video play button:

<button onClick={()=>videoElement.target.playVideo()}> Play Video </button> 
Enter fullscreen mode Exit fullscreen mode

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> ); 
Enter fullscreen mode Exit fullscreen mode

Source code: Github
Website: Personal site
⚡Thanks for reading, see you in the next blog.

Top comments (1)

Collapse
 
vipdn02 profile image
vipdn02

the music songs is not working in mobile
can you fix it?