Proper download for <audio>

I look around and I start to worry that this is impossible.
Is there any way to make a standard <audio> with backups ...

 <audio> <source src='song.ogg' type='audio/ogg'></source> <source src='song.mp3' type='audio/mp3'></source> </audio> 

... there is an onload event. I looked around and all I could find were some hacks that may or may not work (they are not for me in Chrome) and the canplaythrough event.
The reason I want this is because I am making a presentation, which has a lot of sound clips for playing at certain moments. I don’t want the presentation to start until all the audio has loaded (otherwise the situation may go out of sync). I want the clips to be downloaded one at a time so that I can create a kind of loading bar. I really do not want to resort to the use of Flash sound, because this should demonstrate pure web technology. So basically I have this loadAudio function that cycles through an array of loaded audio files audioQueue . loadAudio is called once, and then it calls itself until all files are loaded. The problem is that I did not find the correct event to load the next file.

 loadAudio = function(index) { mer = audioQueue[index]; var ob = "<audio id='" + mer + "'><source src='resources/sounds/" + mer + ".ogg' type='audio/ogg'></source><source src='resources/sounds/" + mer + ".mp3' type='audio/mp3'></source></audio>"; $("#audios").append(ob); $("#" + mer).get(0).addEventListener('A WORKING EVENT RIGHT HERE WOULD BE NICE', function() { alert("loaded"); if (index + 1 < audioQueue) { loadAudio(index + 1); } }, false); } 

So. Is there a chance that the sound will load correctly? I'm basically ready to do anything while it still contains HTML and Javascript.

+4
source share
2 answers

You can use loadeddata - MediaEvent . For example, you can put all your audio files in an array and do something like:

 var files = ['a.mp3', 'b.mp3']; $.each(files, function() { $(new Audio()) .on('loadeddata', function() { var i = files.indexOf(this); files.splice(i, 1); if (!files.length) { alert('Preloading done!'); } }) .attr('src', this); }); 

EDIT : this will be a slightly more modern approach from 2016:

 var files = ['a.mp3','b.mp3']; Promise .all(files.map(function(file) { return new Promise(function(resolve) { var tmp = new Audio(); tmp.src = file; tmp.addEventListener('loadeddata', resolve); }); })).then(function() { alert('Preloading done!'); }); 
+7
source

I made a little PONG game with WebGL and some audio tags for sounds. I borrowed an audio implementation from an Opera Emberwind HTML5 implementation: https://github.com/operasoftware/Emberwind/blob/master/src/Audio.js

Their solution works fine for me (Chrome, Opera and Firefox). Maybe this may interest you? They have code that will try to find a reproducible format from line 22 and below.

+2
source

Source: https://habr.com/ru/post/1401309/


All Articles