Javascript audio onload

I did a javascript audio test. The whole function works in Opera FF and Chrome, except audio.oncanplaythrough and audio.onended (this function does not work in Chrome).

<!DOCTYPE html> <html> <body> <script> var audio = new Audio("http://www.w3schools.com/html5/song.ogg"); audio.oncanplaythrough = function(){ audio.play(); } audio.onended = function(){ alert('ended'); } </script> <a href="#" onclick="audio.play();">start</a><br/> <a href="#" onclick="audio.pause();">pause</a><br/> <a href="#" onclick="audio.volume=prompt('from 0 to 1',0.7)">volume</a><br/> <a href="#" onclick="audio.currentTime = 3;">jump</a><br/> </body> </html> 
+4
source share
2 answers

oncanplaythrough is an event, not a method, and another event is called ended , not onended .

So, you need to listen to events and act on them. Try:

 audio.addEventListener('ended', function() { alert('ended'); }, false); 

and

 audio.addEventListener('canplaythrough', function() { audio.play(); }, false); 
+14
source

Add and play sound through JavaScript

 var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'loading.ogg'); audioElement.play(); 

Get the path and duration of a song file

 audioElement.src; audioElement.duration; 

Download sound

 var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'Mogwai2009-04-29_acidjack_t16.ogg'); audioElement.load() audioElement.addEventListener("load", function() { audioElement.play(); $(".duration span").html(audioElement.duration); $(".filename span").html(audioElement.src); }, true); 

Stop song

 audioElement.pause(); 

Change volume

 audioElement.volume=0; 

Play exactly 35 seconds in a song

 audioElement.currentTime=35; audioElement.play(); 
+3
source

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


All Articles