AzanKorejo
AzanKorejo

Reputation: 38

how to play two audio files with same id with javascript

i have two audio files with progress bar and both having same id:

<audio id="player" src="<?=base_url('mp3/'.$rec->file)?>"></audio>
                    </p>
                            <button class="btn btn-success btn-sm" id="play">
                            <svg style='font-size: 1.3em' class="bi bi-play-fill" width="1em" height="1em" 
                                viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                <path d="M11.596 8.697l-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.692-1.01 1.233-.696l6.363 3.692a.802.802 0 010 1.393z"/>
                            </svg>
                        </button>
                        <button class="btn btn-secondary btn-sm" id="pause">
                            <svg style='font-size: 1.3em' class="bi bi-pause-fill" width="1em" height="1em" viewBox="0 0 16 16" 
                                fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                              <path d="M5.5 3.5A1.5 1.5 0 017 5v6a1.5 1.5 0 01-3 0V5a1.5 1.5 0 011.5-1.5zm5 0A1.5 1.5 0 0112 5v6a1.5 1.5 0 01-3 0V5a1.5 1.5 0 011.5-1.5z"/>
                            </svg>
                        </button>
                        <progress style="height: 4px;border: none;width: 300px;max-width: 330px" id="seekbar"  value="0" max="1">ssss

And Here's js

  <script type="text/javascript">
$('#play').on('click', function() {
    document.getElementById('player'.).play();
});

$('#pause').on('click', function() {
    document.getElementById('player').pause();
});

$('#player').on('timeupdate', function() {
    $('#seekbar').attr("value", this.currentTime / this.duration);
});
</script>

now i am able to play the first audio file but cannot play second file

how do i do that?????

if there's any other solution like looping ids or anything just tell me because i am a noob in js

enter image description here

Upvotes: 0

Views: 283

Answers (1)

Hao Wu
Hao Wu

Reputation: 20699

document.getElementById only returns the first match, if you want to get all matches, use document.querySelectorAll instead.

Here's how you should do it

$('#play').on('click', function() {
    [...document.querySelectorAll('#player')].forEach(e => e.play());
});

$('#pause').on('click', function() {
    [...document.querySelectorAll('#player')].forEach(e => e.pause());
});

As kerbholz mentioned, id should be unique. If it meant to have multiple instances, consider to use class instead.

Upvotes: 1

Related Questions