Playing multiple looping sounds on a website - javascript

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.

Related

Plyr audio player muted for the first second of audio

I am using Plyr audio player for my Rails app, along with Simulus.js.
I dynamically add audio source when the user clicks on different audio buttons. Then I launch the audio player with the .play() method.
However, the beginning of the track can't be heard. You can try it out on this URL, by taping the first audio player. If you put back the audio cursor to the beginning, then you can hear the very beginning of the track.
Here is my HTML:
<audio class="player" controls data-dicteeModule-target="player">
<source class="player-source" src="<%= dictee_modules.first.audio_url %>" type="audio/mp3" />
</audio>
Here is how I initialize the player:
initialize() {
const players = document.getElementsByClassName('player');
var player = [];
Array.from(players).forEach(function (ele, i) {
player[i] = new Plyr(ele, {
controls: ['progress']
});
});
}
Here is my Stimulus onclick action:
var player = this.playerTarget;
var source = audio.getAttribute("data-audio-source");
var audioSource = player.getElementsByClassName("player-source")[0];
audioSource.src = source;
player.load();
player.addEventListener('canplay', (event) => {
player.play();
});
Any idea why the very beginning of the track is not heard?
Thanks.
This happens to me too on various websites that need to use audio after no audio was used for a while, even on YouTube. I'm using Chrome 104.0.5112.81 on Windows 10.
It's likely a driver issue you can't do much about (assuming YouTube would fix it if they could). It looks like Windows or Chrome ends up dimming the sound way too quickly, and takes too long turning it back on.
Unfortunately I couldn't find anything on Google yet. It seems hard to make Google understand this query, it only returned results about audio preventing PC sleep mode (or other unrelated common issues), no matter how I phrased it. Could also indicate it's just a very obscure issue with one or a few particular drivers.

add audio in html without <audio> element (preferebly js)

I'm wondering if we can make audio in html without the tag. perhaps we could have buttons for play and pause but still I don't know how to control volume, etc. I searched up other websites, And couldn't find the answer.
thanks,
Smit
You can use javascript to dynamically edit the attributes of audio.
Here is a list of functions:
myaudio.play(); - This will play the music.
myaudio.pause(); - This will stop the music.
myaudio.duration; - Returns the length of the music track.
myaudio.currentTime = 0; - This will rewind the audio to the beginning.
myaudio.loop = true; - This will make the audio track loop.
myaudio.muted = true; - This will mute the track
Like this there are many functions, please go through the documentation at W3C.
You can use tag to add the audio in your website. It comes with the Controls attribute as well.
This website might be helpful for you:
http://www.webreference.com/js/column20/control.html

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.

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

html5 video playing twice (audio doubled) with JQuery .append()

Huge WTF that I thought was a bug hidden in the semicomplex web app that I'm making, but I have pared it down to the simplest code possible, and it is still replicable in Firefox, Chrome, and Safari, unpredictably but more than 1/2 of the time.
http://jsfiddle.net/cDpV9/7/
var v = $("<video id='v' src='http://ia600401.us.archive.org/18/items/ForrestPlaysTaik/forresto-plays-taik-piano-360.webm' autobuffer='auto' preload autoplay controls></video>");
$("#player").append(v);
Add a video element.
Video starts to load and play.
Video audio sounds like it is doubled.
Pause the visible video, and one audio track continues.
Delete the video element; the ghost audio keeps playing.
Delete the frame, and the ghost audio stops (though once in Firefox it continued to play after closing the window, and didn't stop until quitting Firefox).
Here is a screen capture to maybe show that I'm not completely crazy: http://www.youtube.com/watch?v=hLYrakKagRY
It doesn't seem to happen when making the element with .html() instead of .append(), so that's my only clue: http://jsfiddle.net/cDpV9/6/
$("#player").html("<video id='v' src='http://ia600401.us.archive.org/18/items/ForrestPlaysTaik/forresto-plays-taik-piano-360.webm' autobuffer='auto' preload autoplay controls></video>");
I'm on OS X 10.6.7.
I think that I have it. Even just creating the JQuery object without adding it to the page causes the ghost player to play: http://jsfiddle.net/cDpV9/8/
var v = $("<video id='v' src='http://ia600401.us.archive.org/18/items/ForrestPlaysTaik/forresto-plays-taik-banjo-360.webm' autobuffer='auto' preload autoplay controls></video>");
For now I can work around this by using .html(). I'll report the issue to JQuery.
Maybe jQuery caches the content of $() before appending it to your player div? So there is another instance of the video tag. It could be an error in jQuery. Have you tried this without Jquery/js?
I would try adding the autoplay attribute after you append the video player. This should then instantiate the play function.
That would be something like this:
var v = $("<video id='v' src='videofile.webm' autobuffer='auto' preload controls></video>");
$("#player").append(v);
v.attr('autoplay','autoplay');
When you create elements in JavaScript i.e. image elements, objects etc, they are loaded instantly and stored in memory as objects. That is why you can preload images before you load a page. It is therefore not a jQuery bug.
Ref: http://www.w3.org/TR/html5/video.html#attr-media-autoplay
When present, the user agent (as described in the algorithm described
herein) will automatically begin playback of the media resource as
soon as it can do so without stopping.
I've got the same problem over here. This seems to be an issue with using the "autoplay" attribute on your video markup.
Remove the autoplay attribute
append your video DOMNode to any node
if you want autoplay behavior, call videodomnode.play() - using jquery this would be $('video')[0].play()
You could get the html of #player and append the video your self, then add the total with .html() like this:
var v = $("#player").html() + "<video id='v' src='http://ia600401.us.archive.org/18/items/ForrestPlaysTaik/forresto-plays-taik-piano-360.webm' autobuffer='auto' preload autoplay controls></video>";
$("#player").html(v);
It's not as good as the .append() function, but if the .append() doesn't work, you might be forced to do something like this.
This one worked best in my case:
var v = '<audio hidden name="media"><source src="text.mp3"><\/audio>';
$('#player').append(v);
$("audio")[$('audio').size()-1].play();
I solved mine by loading video after dom loaded:
$(window).bind("load", function() {
var v = $("<video id='bgvid' loop muted>
<source src='/blabla.mp4' type='video/mp4'>
</source>
</video>");
$(".video-container").append(v);
v.attr('autoplay','autoplay');
});

Categories

Resources