How to play a sound with JS? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Playing sound notifications using Javascript?
I'm making a game in JS, and I need a proper way to play a sound when something happens. How do you do that with JS/HTML5? I saw this article, but even with their example, it doesn't really work! Sometimes I do hear that bird, but only for a short time, and I can't get it to work anymore then.

HTML5 has the new <audio>-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface:
<audio id="sound1" src="yoursound.mp3" preload="auto"></audio>
<button onclick="document.getElementById('sound1').play();">Play it</button>

You can make use of the HTML5 <audio> tag: http://jsfiddle.net/STTnr/.
var audio = document.getElementById('audio');
setTimeout(function() {
audio.play(); // play it through JavaScript after 3 seconds
}, 3000);
HTML:
<audio src="something" id="audio"></audio>
Just hide the element itself:
#audio {
display: none;
}
Do note that no browser supports all formats. This can be frustrating, but you can supply your audio in several formats.

Related

Playing multiple looping sounds on a website

Is there a 'best way' to play sounds/music on a website? Should I use JS plugin? SWF app or a HTML element? Also I want it to support volume that can be controlled via HTML slider.
If I want to play multiple sounds/music on top of each other do I have to have a 'player' for each one of them or can I have one player playing multiple sounds?
Last time I needed to add sounds to my website was like 10 years ago so I have no idea what techniques people use nowadays.
It's actually very simple. HTML5 makes it easy by introducing the <audio> tag.
This uses the default audio controls:
<audio loop controls><source src="yoursoundhere.mp3" type="audio/mpeg"></audio>
The loop attribute makes it auto-loop. Add the autoplay attribute if you want it to start playing on load. Multiple audio tags play over each other.
Note that this only works with MP3. Otherwise, you need to change the type of file.
If you want a custom slider, here is something you could try:
<audio loop id="audio"><source src="yoursoundhere.mp3" type="audio/mpeg"></audio>
<script>
//When slider value updates.
function updateSlider(){
var audioplayer = document.getElementByID("audio");
var controlvalue = yourHTMLsliderValue();
audioplayer.volume = controlvalue;
}
//First Time.
var audioplayer = document.getElementByID("audio");
var controlvalue = yourHTMLsliderValue();
audioplayer.volume = controlvalue;
</script>
Also note that the supported audio filetypes are .mp3, .ogg, and .wav, and that this only works in HTML5.

Game development: restart the sound(<audio> element) before it ended playing

I ran into some issues regarding my small-web-game project:
I have some sound files, given in HTML like this:
<audio id="shotSound" preload="auto">
<source src="../sound/shot.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
the preload="auto" should load the content immediately on page init right?
Now I'm using javascript to trigger the sound when I need to (key press):
var audio = document.getElementById("shotSound");
audio.play();
This works, but if I try to shot continuously or just faster(one shot after another) it won't work for shots after the first one. So, what happens if I hold the "shot" button: the sound is heard like it would be on repeat - which is obviously wrong.
Any ideas/suggestions are very welcome!
If I was unclear, please do let me know.
Thank you
Don't put the audio-tag into the HTML document. Preload the sound-effect in Javascript using
shotSound = new Audio();
shotSound.src = "../sound/shot.mp3";
shotSound.load();
Keep the shotSound variable in scope, so it doesn't get garbage-collected. Then, when you need to play a sound, create a new Audio object:
new Audio("../sound/shot.mp3").play();
It will play immediately because the sound-file will already be cached. And because it's a new audio-object, it won't interrupt other instances of the same effect playing in parallel.

HTML5 Video Intro? [duplicate]

This question already has answers here:
Redirect html5 video after play
(7 answers)
Closed 9 years ago.
so I want to have a short video intro for my website then it will go fade out and straight to my main site. Sorta like this: http://www.firecrackerfilms.com/.
This is my Code:
<video id="video" src="Inception.mp4" autoplay height: 100% width=100%>
The video works fine but after it finishes it just stays there and doesn't go to the main page. Any tips or solutions would be greatly appreciated!
Thanks!
In window.onload, bind an event handler to the video element's "ended" event. In that handler, you can either redirect the page or load content with AJAX. Something like:
window.onload= function () {
document.getElementById("video").onended = function () {
// video done playing
};
};

Playing random audio in HTML/Javascript

I am trying to figure out how to continuously play random audio sound bites, one after another without having them overlap on an HTML page using jquery. I have code that plays random sound bites on a timer, but sometimes they overlap and sometimes there is a pause in between the sounds. I had looked into ended and other EventListeners but I really have no idea what I am doing. Here is a portion my code:
<html>
<audio id="audio1">
<source src="cnn.mp3"></source>
</audio>
<audio id="audio2">
<source src="sonycrackle.mp3"></source>
</audio>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('audio').each(function(){
this.volume = 0.6;
});
var tid = setInterval(playIt, 2000);
});
function playIt() {
var n = Math.ceil(Math.random() * 2);
$("#audio"+n).trigger('play');
};
Is there a way to just continuously play these sounds bites one after another right after the previous sound plays? FWIW I have many sound bites but I am just showing two above for reference.
So I dabbled a bit, here's a full pure JavaScript solution.
Should be cross-browser, haven't tested (/lazy). Do tell me if you find bugs though
var collection=[];// final collection of sounds to play
var loadedIndex=0;// horrible way of forcing a load of audio sounds
// remap audios to a buffered collection
function init(audios) {
for(var i=0;i<audios.length;i++) {
var audio = new Audio(audios[i]);
collection.push(audio);
buffer(audio);
}
}
// did I mention it's a horrible way to buffer?
function buffer(audio) {
if(audio.readyState==4)return loaded();
setTimeout(function(){buffer(audio)},100);
}
// check if we're leady to dj this
function loaded() {
loadedIndex++;
if(collection.length==loadedIndex)playLooped();
}
// play and loop after finished
function playLooped() {
var audio=Math.floor(Math.random() * (collection.length));
audio=collection[audio];
audio.play();
setTimeout(playLooped,audio.duration*1000);
}
// the songs to be played!
init([
'http://static1.grsites.com/archive/sounds/background/background005.mp3',
'http://static1.grsites.com/archive/sounds/background/background006.mp3',
'http://static1.grsites.com/archive/sounds/background/background007.mp3'
]);
Some quick suggestions is add the attribute preload="auto" to the audio element and change the script to be $(window).onload instead of document ready. Document ready fires when html is in place but not necessarily when audio and other assets (like images) have loaded.
You could also look into using the AudioBuffer Interface in the new Web Audio API, it's described as "this interface represents a memory-resident audio asset (for one-shot sounds and other short audio clips)." which sounds like what you need. I believe part of the issues you're having (random pauses/delays/sound glitches with the audio element) are one of the reasons why it's being developed.
Read more here:
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioBuffer
Unfortunately it's only Chrome and lastest Safari supported with Firefox support supposedly in the next 6(ish) months and no word yet on IE support.

HTML 5 <audio> - Play file at certain time point

I have a simple auto playing snippet that plays the audio file however I was wondering either in JavaScript or as an attribute play that file at a certain time (ex. 3:26).
<script type="text/javascript">
var myAudio=document.getElementById('audio2')
myAudio.oncanplaythrough=function(){this.play();}
</script>
<audio id="audio2"
preload="auto"
src="file.mp3"
oncanplaythrough="this.play();">
</audio>
Any help would be great. Thanks in advance :)
The best way to do this is to use the Media Fragment URI specification. Using your example, suppose you want to load the audio starting at 3:26 in.
<audio id="audio2"
preload="auto"
src="file.mp3#t=00:03:26"
oncanplaythrough="this.play();">
</audio>
Alternatively, we could just use the number of seconds, like file.mp3#t=206.
You can also set an end time by separating the start from the end times with a comma. file.mp3#t=206,300.5
This method is better than the JavaScript method, as you're hinting to the browser that you only want to load from a certain timestamp. Depending on the file format and server support for ranged requests, it's possible for the browser to download only the data required for playback.
See also:
MDN Documentation - Specifying playback range
W3C Media Fragments URI
A few things... your script will first need to be after the audio tag.
Also you don't need the oncanplaythough attribute on the audio tag since you're using JavaScript to handle this.
Moreover, oncanplaythrough is an event, not a method. Let's add a listener for it, which will instead use canplaythough. Take a look at this:
<audio id="audio2"
preload="auto"
src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg" >
<p>Your browser does not support the audio element</p>
</audio>
<script>
myAudio=document.getElementById('audio2');
myAudio.addEventListener('canplaythrough', function() {
this.currentTime = 12;
this.play();
});
</script>
And finally, to start the song at a specific point, simply set currentTime before you actually play the file. Here I have it set to 12 seconds so it will be audible in this example, for 3:26 you would use 206 (seconds).
Check out the live demo: http://jsfiddle.net/mNPCP/4/
EDIT: It appears that currentTime may improperly be implemented in browsers other than Firefox. According to resolution of this filed W3C bug, when currentTime is set it should then fire the canplay and canplaythrough events. This means in our example, Firefox would play the first second or so of the audio track indefinitely, never continuing playback. I came up with this quick workaround, let's change
this.currentTime = 12;
to test to see if it has already been set, and hence preventing the canplaythrough to get called repeatedly:
if(this.currentTime < 12){this.currentTime = 12;}
This interpretation of the spec is still currently being disputed, but for now this implementation should work on most modern browsers with support for HTML5 audio.
The updated jsFiddle: http://jsfiddle.net/mNPCP/5/
I have a simple answer that will work for all
1- create a button that when clicked it plays the audio/video
2- test that audio playing when you click the button if it works to hide the button and
3- click button when page loads
window.onload =function(){
document.getElementById("btn").click();
}

Categories

Resources