Javascript Audio Play on click - javascript

I have a JavaScript code to play a sound on click.
It works on Chrome but on Firefox it starts on load.
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()">

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>

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.

You can do that in two line
let playSound = () => new Audio("src").play()
<button onclick="playSound()">Play</button>

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()}

Related

How to save audio files on browser's cache so that when the user press a button, the audio starts playing immediately from cache?

I have a collection of short audio files, and I want to play one audio file when the user press a corresponding button. I have this script to play a sound:
<script type="text/javascript">
var sound = new Audio();
function playSound(audioUrl) {
sound.src = audioUrl;
sound.play();
}
</script>
<button type="button" onclick="playSound('http://example.com/audioA.mp3')">Audio A</button>
<button type="button" onclick="playSound('http://example.com/audioB.mp3')">Audio B</button>
<button type="button" onclick="playSound('http://example.com/audioC.mp3')">Audio C</button>
...
The problem is, these audio files are not large, but still need a short delay to download and play at the first time the button pressed, which kinda annoying. How do I command the browser to cache all the audio files on page load? When I search about this I found about buffering and streaming audio, which might not suit my needs as my audio lengths are not that long. Thanks.
You can preload them and then make the link available as soon is preloading is complete. You can do this synchronous or asynchronous. I recommend to do it asynchronous.
Look at this example:
var sound = new Audio();
function playSound(audioUrl) {
sound.src = audioUrl.getAttribute('data-url'); //grab the data-url
sound.play();
}
function preloadAudio()
{
var audioButtons = document.querySelectorAll("button[data-type='audio']") //select all button elements with data-type = audio
for (var i = 0; i < audioButtons.length; i++)
{
//loop all audio elements
audioButtons[i].setAttribute("disabled", true); //disable the element
var preloader = new Audio();
preloader.addEventListener("loadeddata", enableAudioButton.bind(audioButtons[i]), true); // use bind to link the audio button to the function
preloader.src = audioButtons[i].getAttribute("data-url"); //trigger the download
}
}
function enableAudioButton()
{
this.removeAttribute("disabled"); //reenable the button
}
document.body.addEventListener("load", preloadAudio, true);
<button type="button" data-type="audio" data-url="http://example.com/audioA.mp3" onclick="playSound(this)">Audio A</button>
<button type="button" data-type="audio" data-url="http://example.com/audioB.mp3" onclick="playSound(this)">Audio B</button>
<button type="button" data-type="audio" data-url="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" onclick="playSound(this)">Audio C</button>
I've used a real example (audio C), so you can see the script in function.
Alternatively, you could also use .load() to pre-load the files and then play them like you did it in the code above.

i am trying to play one mp3 file after another (one as intro) but it won't work. How can i do this?

I am trying to use a intro sound for the mp3 files. After playing the intro the original track should start to play. i mean the original mp3 plays right after the intro ends. Here i have this:
<script type="text/javascript" src="js/jquery.min.js"></script>
<audio id='top' onended="playOrg();" preload='none' src='http://www.sounddogs.com/previews/59/mp3/607322_SOUNDDOGS__th.mp3' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'> START </a>
And here the javascript part:
<script type="text/javascript">
var yourAudio = document.getElementById('top');
var ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
var pause = ctrl.innerHTML === 'STOP';
$('.btn').html('START');
$('audio').trigger('pause');
ctrl.innerHTML = pause ? 'START' : 'STOP';
var method = pause ? 'pause' : 'play';
yourAudio [method]();
return false; };
function playOrg(){
yourAudio.setAttribute('onended','orgPlayed()');
yourAudio.src='http://www.sounddogs.com/sound-effects/59/mp3/606540_SOUNDDOGS__sf.mp3';
yourAudio.play();
console.log('playOrg()');
}
function orgPlayed(){
yourAudio.setAttribute('onended','playOrg()');
yourAudio.src='http://www.sounddogs.com/previews/59/mp3/607322_SOUNDDOGS__th.mp3';
yourAudio.pause();
yourAudio.currentTime = 0;
console.log('orgPlayed()');
}
</script>
When i press start the file plays and on the end it calls the playOrg() function witch should change some attributes and should play the original track. Then the second file should play and on its end this time the orgPlayed() function should be called and set back the attributes so that it is ready for the other play.
So i want to use intro track for all my track on the site. But i can't accomplish that. i appreciate any upcoming help.
PS: Actually there is a loop for all tracks in my original code but i summarised it here. Please don't ask why i couldn't find better mp3 test files :).
I found the my problem. Instead of reloading the new track with "currentTime=0" i tried to reload with "load()" , and now it works. I guess sometime we need to sleep over such problems :). Thanks to everyone ;).
<audio id='top' onended="playOrg();" preload='none' src='top10/intro/1.mp3' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'>START</a>
<script type="text/javascript">
var yourAudio = document.getElementById('top');
var ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
if (ctrl.innerHTML=='START') {
ctrl.innerHTML='STOP';
yourAudio.play();
}else if (ctrl.innerHTML=='STOP'){
ctrl.innerHTML='START';
yourAudio.pause();
}
}
function playOrg(){
var myPlayer= document.getElementById('top');
myPlayer.setAttribute('onended','orgPlayed()');
myPlayer.src='top10/tarkan.mp3';
myPlayer.pause();
myPlayer.load();
myPlayer.play();
}
function orgPlayed(){
var myPlayer= document.getElementById('top');
myPlayer.setAttribute('onended','playOrg()');
myPlayer.src='top10/intro/1.mp3';
myPlayer.pause();
myPlayer.load();
ctrl.innerHTML='START';
}
</script>
now i realised another way to solve this. i could use two audio tags with one intro source and the other the original source. and then after the first one ends i could play the second using either a function or directly onended="document.getElementById('top2').play();"
i mean something like this:
<audio id='top1' onended="play second(with a function or directly)" preload='none' src='intro' type='audio/mpeg'> </audio>
<audio id='top2' onended="make ready for another play (with a function or directly)" preload='none' src='original' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'>START</a>

Javascript play sound on hover. stop and reset on hoveroff

function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.Play();
}
function StopSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.Stop();
}
This is my code to play a audio file,
onmouseover="EvalSound('sound1')" onmouseout="StopSound('sound1')"
It is currently working on hover, however when i go back to the image that it plays under it doesnt go back to the beginning, it continues playing
The <embed> tag is the old way to embed multimedia. You really ought to be using the new HTML5 <audio> or <video> tags as they are the preferred and standardized way to embed multimedia objects. You can use the HTMLMediaElement interface to play, pause, and seek through the media (and lots more).
Here is a simple example that plays an audio file on mouseover and stops it on mouseout.
HTML:
<p onmouseover="PlaySound('mySound')"
onmouseout="StopSound('mySound')">Hover Over Me To Play</p>
<audio id='mySound' src='http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg'/>
Javascript:
function PlaySound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function StopSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.pause();
thissound.currentTime = 0;
}
For more information, check out the MDN guide for embedding audio and video
I had the same question, about starting and stopping audio. I use jQuery without any other plugins. My code is for mousedown and mouseup, but could be changed to other actions.
HTML
<div class="soundbutton">
cool wind sound
</div>
<audio id="wind-sound" src="wind-sound/wind.mp3">
Javascript
$('.soundbutton').on('mousedown', function () {
playWind(); //start wind sound
})
.on('mouseup', function () {
stopWind(); //stops the wind sound
});
// my full functions to start and stop
function playWind () { //start wind audio
$('#wind-sound')[0].volume = 0.7;
$('#wind-sound')[0].load();
$('#wind-sound')[0].play();
}
function stopWind () { //stop the wind audio
$('#wind-sound')[0].pause();
$('#wind-sound')[0].currentTime = 0; //resets wind to zero/beginning
}
<html>
<script>
function stopAudio() {
player.pause();
player.currentTime = 0;
}
</script>
<body>
<audio id="player" src="(place audio here)"></audio>
<div>
<button onclick=" stopAudio()">Stop</button>
</div>
</body>
</html>
//End Note: you must look at your audio id as mine is named "player"
this is the reason it is not working look at your css and your html
very closely in your lines. The other thing you must be careful about
is your call function as mine is stated as stopAudio() yours could be
named different. The function only works with css if you use your call
method properly.

sound effect in a html5 game

I'm trying to play sound effect in a game with each hit,but the sound sometimes play and others NOT !!
I'm using the next code :
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.loop = false;
hitSound.currentTime = 0;
hitSound.play();
}
</script>
<audio id="effects" hidden>
<source src="sound/mp3/effect.mp3" type="audio/mpeg">
<source src="sound/wav/effect.wav" type="audio/wav">
</audio>
any ideas ?
Whenever you are using audio tag try writing its script after audio tag ,If you write script before that audio tag it gives sometime problem in playing the audio,
i would recommend Write Script at the end of the page that's the standard way to write script.
http://jsfiddle.net/LyDWH/4/
<!DOCTYPE html>
<html>
<body>
<audio id="effects" hidden >
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<div onclick= "playEffectSound();">Horse Click Me..!</div>
</body>
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.currentTime = 0;
hitSound.play();
}
</script>
</html>
​
You could use the following code to play audio
function playEffectSound(sound) {
//Does the sound already exist?
if (document.getElementById(sound) != null) {
document.getElementById(sound).play();
return;
}
//Create elements
var audioElement = document.createElement("audio");
var sourceElement = document.createElement("source");
sourceElement.src = sound + ".mp3";
sourceElement.type = "audio/mpeg";
var sourceElementWave = document.createElement("source");
sourceElementWave.src = sound + ".wav";
sourceElementWave.type = "audio/wav";
//Add sources to audio
document.body.appendChild(sourceElementWave);
document.body.appendChild(audioElement);
audioElement.setAttribute("id", sound);
audioElement.appendChild(sourceElement);
audioElement.loop = false;
audioElement.currentTime = 0;
audioElement.play();
}
You can use it like this: playEffectSound("sounds/effect"); and it will either play sounds/effect.mp3 or sounds/effect.wav
try with each hit to add a new var sound and sound.play() and it will just work fine

Adding audio to click event

I want to add a sound clip to a button on a game I am creating. Currently It doesn't do anything and I don't know why.
At the moment In the script I have...
var audio = $(".mysoundclip")[0];
$(".minibutton").onclick(function() {
audio.play();
});
In the HTML I have...
<audio id="mysoundclip" preload="auto">
<source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
Then I have CSS for .minibutton.
Any ideas why it won't work?
Your jQuery had some simple errors in it.
HTML
<audio id="mysoundclip" preload="auto">
<source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
<button type="button">play</button>
jQuery
var audio = $("#mysoundclip")[0];
$("button").click(function() {
audio.play();
});​
Fiddle: http://jsfiddle.net/iambriansreed/VavyK/
​
Maybe I'm a too suspicous.. but
http://www.sound-effect.com/sounds1/animal/Saf/Tiger1.wav "The requested URL was not found on this server"
If that's just a typo, you should also try to figure out which audio types a browser is capable to play:
myApp.htmlAudio = (function _htmlAudioCheck() {
var elem = document.createElement('audio'),
bool = false;
try {
if( !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
bool.mp3 = elem.canPlayType('audio/mpeg;');
bool.wav = elem.canPlayType('audio/wav; codecs="1"');
bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;'));
}
} catch(e) { }
return bool;
}());
Now we can check like
if( myApp.htmlAudio && myApp.htmlAudio.wav ) {
}
if the browser is able to playback .wav files for instance.
However, I never saw a nested source element for audio elements. That should be named track if anything. But you don't really need that here, you can just have a src attribute on the audio element itself. Example: http://jsfiddle.net/5GUPg/1/

Categories