Uw001
Uw001

Reputation: 363

javascript audio onload

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>

Upvotes: 8

Views: 41046

Answers (2)

Ian Devlin
Ian Devlin

Reputation: 18870

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

Upvotes: 22

LPunker
LPunker

Reputation: 613

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

Upvotes: 4

Related Questions