5

I have tried two version

The first one autoplay is working on Google Chrome but how can I control with button that I can play or pause the audio?

 <embed name="pop" src="pop.mp3" loop="true" hidden="true" autostart="true">

The second one autoplay is not working on Google Chrome but I can control it with button in IE or FireFox

<audio id="myAudio">
<source src="pop.mp3" type="audio/mp3">
</audio>

The buttons

<button onclick="playAud()" type="button">Play</button>
<button onclick="pauseAud()" type="button">Pause</button>

And the Javascript

var aud = document.getElementById("myAudio"); 

function playAud() { 
aud.play(); } 

function pauseAud() { 
aud.pause(); } 

So how can I deal with this problem?

I want the Audio autoplay in background
And then I can use button to play or pause it

TheRyuuSei
  • 65
  • 5

2 Answers2

0

Try this:

<audio id="sound" src="sound.mp3" autoplay="0" autostart="0"></audio>
<button onclick="playAud()" type="button">Play</button>
<button onclick="pauseAud()" type="button">Pause</button>

<script>
    let aud = document.getElementById("sound");

    function playAud() { 
        aud.play(); 
    } 

    function pauseAud() { 
        aud.pause(); 
    } 
Jaden Baptista
  • 656
  • 5
  • 16
0

You only have to trigger the play function on init:

var aud = document.getElementById("myAudio");

function play() {
  aud.play();
}

function pause() {
  aud.pause();
}

aud.play(); // this will do the trick :)
<audio id="myAudio">
<source src="https://wiki.selfhtml.org/local/Europahymne.mp3" type="audio/mp3">
</audio>
<button onclick="play()" type="button">Play</button>
<button onclick="pause()" type="button">Pause</button>

Old solution:

You could remove/add your embed-element like i did here. This might be hacky, but it could be a solution for you.

var audiowrapper = document.getElementById('audio-wrapper');
var audio = document.getElementById('audio');

function play() {
  if (!audiowrapper.hasChildNodes()) audiowrapper.appendChild(audio);
}

function pause() {
  if (audiowrapper.hasChildNodes()) {
    while (audiowrapper.firstChild) {
      audiowrapper.removeChild(audiowrapper.firstChild);
    }
  }
}
#audio-wrapper {
  position: absolute;
  top: -300px !important;
}
<div id="audio-wrapper">
  <embed id="audio" name="pop" src="https://wiki.selfhtml.org/local/Europahymne.mp3" loop="true" hidden="true" autostart="true">
</div>
<button onclick="play();" type="button">Play</button>
<button onclick="pause();" type="button">Pause</button>
jsadev.net
  • 2,800
  • 1
  • 16
  • 28