how to break instance of previous song?

159 Views Asked by At

I am making an audio player in reactjs that looks like this app, song box is rendered in map function and on click on any song box it start playing, but the problem is when click on next song to change the track, the audio src value gets changed but previous song did not stop playing,

any Help?


function playMusic(audio: HTMLAudioElement) {}

function handleMusicPlayer(index: number) {

    let audio = new Audio(props.musicData[index].track.preview_url);
    audio.play();
    playMusic(audio);

    if (musicMinimize) {
        props.onPlay(false);
        setmusicMinimize(false);
        setTimeout(() => {
            setmusicMinimize(true);
            props.onPlay(true);
        }, 1000);
    } else {
        props.onPlay(false);
        setmusicMinimize(true);
    }
    
    props.onCurrent({
        image: props.musicData[index].track.album.images[0].url,
        name: props.musicData[index].track.name,
        track: props.musicData[index].track.preview_url
    });

}

function handleMusicPlayer get run when song box clicked, and function playMusic should control the playing of current and next song

2

There are 2 best solutions below

10
imtaki company On

You can solve it with stopping all audios in that page before start new one:

Here is example;

const player = document.getElementById('player');
player.addEventListener('click', (event) => {
var myId    = event.target.getAttribute('href');
var audio   = document.getElementById(myId);
document.querySelectorAll('audio').forEach(sound => {
sound.pause();
});
audio.play();
})
<audio id="myAudio" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"></audio>
<audio id="myAudiotwo" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>


<p>Click the buttons to play or pause the audio.</p>
<div id='player'>
<button  href="myAudio" type="button">Play Audio</button>
<button  href="myAudiotwo" type="button">Play Audio</button>
</div>

0
abhi jain On
const ref = useRef(new Audio());

ref.current.pause()

ref.current = new Audio("new_song");

ref.current.play()