Playing audio from a playlist in React

Viewed 572

Radio playlist Using plyr-react module
Data from an API json file, get the data as a playlist and load it into the Plyr Audio player.

Trying to figure out how the url can be passed to the Plyr source path. Cant get the source url loaded into the Audio player. Following is the code

import React, { useEffect, useState } from 'react';
import Radioplyr from 'plyr-react';

const tracks = {
    type: "audio",
    sources: [
      {
        src: "https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",
      },
      {
        src: "http://172.105.50.82/radio/8000/radio.mp3",
      },
      
    ]
  };
const audioSrc =  {
  type: "audio",
  sources: [
    {
      src: {playlist},
    },
    
  ]
};
return (
  <div>
    <Radioplyr source={audioSrc} />
    {playlist} 
    <ul className="playlist">
        {tracks.sources.map((item, i) => {
          return <li key={i}><a onClick={() => setPlaylist(item.src)}>{item.src}</a></li>
        })}
      </ul>
  </div>
);
}
1 Answers

Use useState for current Track Source

const [currentTrackSrc, setCurrentTrackSrc] = useState(tracks.sources[0])

const [audioSrc, setAudioSrc]=  useState({
  type: "audio",
  sources: [
    {
      title: currentTrackSrc.title,
      src: currentTrackSrc.src,
    },
    
  ]
});
const changeOnDemandSong = (newSong, newSongTitle) => {
  setCurrentTrackSrc(newSong);
  setAudioSrc({
    type: "audio",
    sources: [
      {
        title: newSongTitle,
        src: newSong,
      },
    ]
  });
}

Onclick event changeOnDemandsong

<div className="">{audioSrc.sources[0].title}</div>
<ul className="ondemand-plList">
        {tracks.sources.map((item, i) => {
          return <li key={i} className="plItem"><a href="#!" onClick={() => { changeOnDemandSong(item.src, item.title); } }>{item.title}</a></li>
        })}
</ul>
Related