Button to play audio dynamically

Asked

Viewed 106 times

1

I am developing a button to play audio in certain parts for my site, for example to have the narration of certain paragraph, I want to do this dynamically, for example by placing certain class and a date, it will search in the directory for the selected track.

I tried to make a code more or less with the idea that I have in mind of this function

function click(){
$('.audioplay').each(function(i){
    var audioplay = new Audio('urldafaixa');
    audioplay.preload = "auto";
    $(this).click(function(e) {
        e.preventDefault();
        audioplay.currentTime = 0;
        audioplay.play();
        audioplay.volume = 1;
        $(this).data("audio-click");
    });
});
}  
  • 1

    What’s the doubt? The error code? It doesn’t work as you expect?

  • So it works, but every time I insert an audio I will have to create a different variable, for example audioplay2, 3 and so on, what I wanted was a way to insert several audios in different places of the page without having to replicate this function, so I thought I’d create a date, maybe make the date pick up the track url, but I’m not getting it done

  • 1

    @Thi100, you can use the attribute data-, as you quoted, as well as a array to store the Urls of audios.

  • could show me an example ?

  • How do you access each url? This is in HTML? You can give an example of HTML?

1 answer

2


That way, all buttons you create with this class and this attribute will be "touchable"

<html>

<head>
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
        crossorigin="anonymous"></script>

    <style>
        .btnPlayAudio {
            min-width: 200px;
            margin-top: 10px;
            display: inline-block;
        }
    </style>
</head>

<body>
    <div style="text-align: center;">
        
        <button class="btnPlayAudio btn btn-success" data-audiourl="https://www.thesoundarchive.com/starwars/star-wars-theme-song.mp3">
            Start Wars Theme
        </button>
        
        <button class="btnPlayAudio btn btn-warning" data-audiourl="https://www.thesoundarchive.com/starwars/star-wars-cantina-song.mp3">
            Cantina Song
        </button>
        
        <button class="btnPlayAudio btn btn-danger" data-audiourl="https://www.thesoundarchive.com/starwars/imperial_march.mp3">
            Imperial March
        </button>

        <button class="btn btn-primary" onclick="stopAll()" style="margin-top: 15px;">
            Stop All
        </button>

    </div>

    <script>
        var listaAudios = [];

        $(document).ready(function () {
            //já que você quer fazer o carregamento antecipado de tudo, pode fazer isso quando 
            //a página for carregada. Pode ser ruim fazer isso se forem muitos
            //arquivos e muito grandes.

            $('.btnPlayAudio').each(function (e) {
                var url = $(this).attr('data-audiourl');
                var audioPlay = new Audio(url);
                audioPlay.preload = "auto";

                var audioData = {
                    'url': $(this).attr('data-audiourl'),
                    'audioPlayObj': audioPlay
                };

                listaAudios.push(audioData);
            });
        });

        $('.btnPlayAudio').click(function () {
            var url = $(this).attr('data-audiourl');
            for (var i = 0; i < listaAudios.length; i++) {
                if (listaAudios[i].url == url) {
                    var audio = listaAudios[i].audioPlayObj;                        
                    audio.currentTime = 0;
                    audio.volume = 1;
                    audio.play();
                    break;
                }
            }
        });

        function stopAll() {
            for (var i = 0; i < listaAudios.length; i++) {
                listaAudios[i].audioPlayObj.pause();
            }
        }

    </script>

</body>

</html>

  • can improve by signing the callback to know if the audio has already been loaded or not and displaying some feedback on screen for this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.