简体   繁体   中英

Audio played once only in Google Chrome in html

The below code is how I put audio in my webpage. It will play the sound when I received protocol from my slave device.

<script>
function RxProtocol()
 {
    var a = document.getElementById("audio1");
    a.play();
 }

</script>

<body>
<audio id="audio1">
<source src="audio.wav" type="audio/wav">
<source src="audio.mp3" type="audio/mpeg">
audio tag not supported.
</audio>
</body>

It is suppose to play the sound each time it received a protocol. But when I use google Chrome, it just play once only (after refresh/reloading the page) when it received the first protocol. After that it is silence when receive protocols.

Other browser like IE9 or firefox do not have this problem. Do you guys know why?

Try adding addEventListener :

<script>
function RxProtocol()
 {
    var a = document.getElementById("audio1");
    a.play();
 }

document.addEventListener("load", RxProtocol, false);

</script>

Regards, Daniel

We need to load first for Google Chrome:

function RxProtocol()
{
    var a = document.getElementById("audio1");

    if (window.chrome) {
        a.load();
    }

     a.play();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM