Multiple HTML mp3 Player with hrefs

Hello - I have build an Website for an music label where the admin can create projects and in those projects upload multiple mp3 files. If he uploads 1 mp3 file, there will be 1 player and if he uploads 3 files, there are 3.

The code in the project.php template looks like this:

<?php foreach($page->audio() as $audio): ?>
<audio id="audio" controls controlsList="nodownload" src="<?php echo $audio->url() ?>" 
type="audio/mpeg">
</audio>

This is working perfectly, but…
Now what I want to do is some styling. I just want a ‘Play’ button that i can style.
If I do something like this:

<a href="#" onclick="document.getElementById('audio').play()">Play</a>

It only plays the first file, but not the second, because there is only one src as you see above.

Here is an example: http://eriksachse.com/voitax/1

How can I make it so that there will be multiple Play Buttons that don’t play only one file?

LG
Erik

You are using the same ID for all your audio tags. Use a class attribute and a script that finds the audio element next to the button.

Thanks for your reply!
I don’t know how to create classes in an CMS system.
Do I have to use a javascript that creates the element/name/class?

My approach:
I would Copy Paste the html Audio like this:

<audio id="player1" src="<?php echo $audio->url() ?>">
</audio> 
<audio id="player2" src="<?php echo $audio->url() ?>">
</audio> 
<audio id="player3" src="<?php echo $audio->url() ?>">
</audio> 

and in the src he just picks the first file, then the next, and so on.
But this does not really seem innovative, or?

Using a class instead of an ID:

<?php foreach($page->audio() as $audio): ?>
<div class="audio-wrapper">
<audio class="audio" controls controlsList="nodownload" src="<?php echo $audio->url() ?>" 
type="audio/mpeg">
</audio>
<a class="playbutton" href="#"">Play</a>
</div>

Script, just a quick jQuery example:

  $('.playbutton').click(function(e) {
       e.preventDefault;
        var button = $(this);
        button.toggleClass('pause');
        var audio = button.parent().find('audio')[0];     
        if (audio.paused) {
          audio.play();
        } else {
         audio.pause();
        }
    });

This is a matter of your Javascript, not a Kirby thing.

1 Like

PERFECT!
Thanks :kiss::honeybee::snail::mushroom::fire: