I have a javascript code to start a sound on click . It works on chrome but on firefox it starts onload, but I want it onclick there too.
Can anyone help?
<script>
var audio = new Audio("http://music.ogg" ) ;
audio.oncanplaythrough = function(){
audio.play();
}
audio.loop = true;
audio.onended = function(){
audio.play();
}
</script>
<input type="image" src="http://button.png" onclick="audio.play()">
This question is related to
javascript
audio
onclick
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.
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>
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.
While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)
An easy fix:
var music = new Audio();
function playMusic(file) {
music.pause();
music = new Audio(file);
music.play();
}
Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).
HTML:
<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>
JavaScript:
let play = function(){document.getElementById("audio").play()}
Source: Stackoverflow.com