1

I'm looking for a way to make html5 audio play as soon as button is clicked. Right now, it does work; but not very reliably.

My file is a 300Kb MP3 (128Kbps) that is hosted on AWS Cloudfront.

<audio id="i-audio" src="https://cdn/url/to/i-audio.mp3" preload="auto" type="audio/mp3"></audio>
this.iAudio = document.getElementById('i-audio');

$("#button").on('click', function() {
  this.iAuido.play();
});

I learn that play() will return a promise; and I'm not sure how can I be sure that audio plays all the time; reliably.

Right now, the play would work at random times or just throw an error.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
TheBigK
  • 233
  • 4
  • 16

1 Answers1

1

If you're getting error messages about Promises and .play(), you'll need to treat .play() as a Promise, see this article.

  • I didn't see any button#button so I'm assuming that's just a typo.

  • this has no context so it'll be referencing window (very useless)

    this.iAudio = document.getElementById('i-audio');
    

    A variable (like var iAudio = ... or const iAudio = ...) should've been declared.

  • this has context of the element listening to the click event

    $("#button").on('click', function() {
      this.iAuido.play();
    });
    

    Can't imagine that this code worked even randomly it just gets worse as I read the next line. Let's assume iAudio is correct and references the <audio> tag, but for some reason this is prefixed to it (wHy?!?). this would reference the button so every segment of a line of code is all sorts of wrong.

const playback = (e) => {
  const mp3 = $('.mp3')[0];
  let action = mp3.paused || mp3.ended ? mp3.play() : mp3.pause();
  return action;
}

playback().then(() => console.log('Promise Resolved')).catch(error => $('.btn').on('click', playback));
button {
  font-size: 5rem;
  color: cyan;
  border: 0;
  background: none;
  cursor: pointer
}

button:focus {
  outline: none
}

button:hover {
  color: tomato;
}
<audio class="mp3" src="https://glsbx.s3.amazonaws.com/-/dd.mp3" preload="auto"></audio>
<button class='btn' type='button'>&#9654;</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
zer00ne
  • 41,936
  • 6
  • 41
  • 68