Home > Enterprise >  Music playback: Enter the music address from the Array and type in onClick
Music playback: Enter the music address from the Array and type in onClick

Time:11-05

Good day. I have a music list that, among the available features, I just want to allow the user to play and pause the music, but I encountered a problem. onClick I have to write a function based on the error I got earlier and I can not write item.url.play() directly, but if I write with function, it will not recognize the item. What is the solution now? You say.

To better understand the codes

 const Musics = [
        {
            name: "это ли счастье",
            img: этолисчастьеImg,
            singer: "Rauf & Faik",
            url: этолисчастьеMusic
        },
        
        //code...
    ];

return (
        <>
            <Box className="list-box">
                {Musics.map((item) =>
                    <Grid container className="box-music">
                        <Grid item lg={3}>
                            <img src={item.img} width="80px" height="80px" className="img-box" />
                        </Grid>
                        <Grid item lg={7} className="text">
                            <Typography>
                                <h5 className="name"> {item.name} </h5>
                            </Typography>
                            <p style={{ color: "#6f009b" }}>{item.singer}</p>
                        </Grid>
                        <Grid item lg={1}>
                            <i className="fa fa-play fa-1x pley" aria-hidden="true" onClick={x}></i>
                        </Grid>
                    </Grid>
                )}
            </Box>
        </>
    );
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Instead of x try

() => yourfunc(item)

You have access to item without calling it directly

CodePudding user response:

First, you need to use an audio element, then on your onClick, you should change the source of audio based on the URL of the song.

first put this on your DOM:

<audio id="audio" controls="controls">
  <source id="audioSource" src=""></source>
  Your browser does not support the audio format.
</audio>   

then in your html:

    <Grid item lg={1}>
       <i className="fa fa-play fa-1x pley" aria-hidden="true" onClick={(e) => {e.preventDefault(); this.play(item.url);}}></i>
    </Grid>

and declare your play method like this:

play(songUrl) {
  const audio = document.getElementById('audio');
  var source = document.getElementById('audioSource');
  source.src = songUrl;
  audio.load(); //call this to just preload the audio without playing
  audio.play(); //call this to play the song right away
}
  • Related