8

I made a javascript audio test. All the function works in Opera FF and Chrome, except audio.oncanplaythrough, and audio.onended (this 2function dont work on 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>
1
  • 1
    This question has nothing to do with onload? Please change title accordingly. Commented Dec 23, 2021 at 10:49

2 Answers 2

21

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

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

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

and

audio.addEventListener('canplaythrough', function() { 
   audio.play();
}, false);
Sign up to request clarification or add additional context in comments.

3 Comments

:D there was a space after 'oncanplaythrough '. Now it works, thanks
So there was (fixed)! Sorry about that. Glad it sorted your problem though.
This should be canplaythrough
3

Add and play a sound via JavaScript

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

Get the song filepath and duration

audioElement.src;
audioElement.duration;

Load a 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 a song

audioElement.pause();

Change volume

audioElement.volume=0;

Play at exactly 35 seconds in the song

audioElement.currentTime=35;
audioElement.play();

2 Comments

... I asked: how to use audio.oncanplaythrough, and audio.onended in Chrome
audio elements do not have a 'load' event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.