Realization of playing Sound on Web Page with js

Click the button to play a tone on the page, thinking that html has an audiu tag, so the initial idea is to dynamically generate an audio to insert into the page. During debugging, it was found that there was a fatal problem. When the page did not operate for a long time, there would be no sound when you click the button (audio has been inserted into the page), but after that, you will have ~

.
Mar.03,2021

write the audio tag directly in html and write a style to hide it.

<audio src='...' style='display:none' id='audio'></audio>

function addVoice(){
    document.getElementById('audio').play();
}

if it's just a simple cue tone, you can refer to this article: use HTML5 Web Audio API to add sound to web JS interaction

in addition, as far as your code is concerned, why not DOM Ready it once and play it over and over again? And do you delete this time in 3 seconds to fit perfectly with the time of the business?


borrow the upstairs code

    <audio autoplay="autoplay" id="audio"></audio>
    <button onclick="addVoice();">play</button>
    <script>
        function addVoice() {
            document.getElementById('audio').src="...";
        }
    </script>
Menu