Javascript Audio Play on click
Solution 1:
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
</body>
</html>
Solution 2:
JavaScript
function playAudio(url) {
new Audio(url).play();
}
HTML
<img src="image.png" onclick="playAudio('mysound.mp3')">
Supported in most modern browsers and easy to embed into HTML elements.
Solution 3:
That worked
<audio src="${ song.url }" id="audio"></audio>
<i class="glyphicon glyphicon-play-circle b-play" id="play" onclick="play()"></i>
<script>
function play() {
var audio = document.getElementById('audio');
if (audio.paused) {
audio.play();
$('#play').removeClass('glyphicon-play-circle')
$('#play').addClass('glyphicon-pause')
}else{
audio.pause();
audio.currentTime = 0
$('#play').addClass('glyphicon-play-circle')
$('#play').removeClass('glyphicon-pause')
}
}
</script>
Solution 4:
Now that the Web Audio API is here and gaining browser support, that could be a more robust option.
Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.
Solution 5:
You can do that in two line
let playSound = () => new Audio("src").play()
<button onclick="playSound()">Play</button>