javascripthtmlaudio-streamingweb-audio-api

How can I solve JavaScript error in playing a song?


This is my JavaScript code >

Array.from(document.getElementsByClassName('songItemPlay')).forEach((element)=>{
    element.addEventListener('click', (e)=>{
        makeAllPlays();
        index = parseInt(e.target.id);
        e.target.classList.remove('fa-circle-play');
        e.target.classList.add('fa-circle-pause');
        audioElement.src = '1/${index}.mp3';
        audioElement.currentTime = 0;
        audioElement.play();
        masterPlay.classList.remove('fa-circle-play');
        masterPlay.classList.add('fa-circle-pause');
    })
})

This is my code for playing an audio file. But the problem is that if I'm playing audio then only my first sound plays and others will not it will stop playing the current sound also.

and this is the folder where I'm having all of my sound tracks C:\Users\Education\Desktop\1 Is there any problem in address I'm using in it or is there any other problem?


Solution

  • Dont know exactly your problem is, but hope this can help you

    I use MP4 and video tag and works fine.

    result enter image description here

    My test html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    
        <style>
            .songItemPlay {
                background-color: black;
                width: 500px;
            }
        </style>
    </head>
    
    <body>
        <video id="C0000001" class="songItemPlay"></video>
        <video id="C0000002" class="songItemPlay"></video>
        <video id="C0000003" class="songItemPlay"></video>
        <video id="C0000004" class="songItemPlay"></video>
        <video id="C0000005" class="songItemPlay"></video>
    
        <script>
            const path = `D:\\temp\\TEST_MP4\\Videos`;
    
            Array.from(document.getElementsByClassName('songItemPlay')).forEach((element) => {
                element.addEventListener('click', (e) => {
                    index = e.target.id;
                    e.target.classList.remove('fa-circle-play');
                    e.target.classList.add('fa-circle-pause');
                    e.target.src = `${path}\\${index}.mp4`;
                    e.target.currentTime = 0;
                    e.target.play();
                })
            })
    
            function makeAllPlays() {
                Array.from(document.getElementsByClassName('songItemPlay')).forEach((element) => {
                    element.play()
                })
            }
    
            makeAllPlays()
        </script>
    </body>
    
    </html>