Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 591
Uw001 Avatar asked Nov 24 '11 12:11

Uw001


People also ask

How do I load audio into JavaScript?

We can load an audio file in JavaScript simply by creating an audio object instance, i.e. using new Audio() . After an audio file is loaded, we can play it using the . play() function. In the above code, we load an audio file and then simply play it.

What is HTMLAudioElement?

The HTMLAudioElement interface provides access to the properties of <audio> elements, as well as methods to manipulate them. This element is based on, and inherits properties and methods from, the HTMLMediaElement interface.

How can I make my audio player invisible in HTML?

The hidden attribute hides the <audio> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <audio> element is not visible, but it maintains its position on the page.


2 Answers

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);
like image 154
Ian Devlin Avatar answered Oct 16 '22 16:10

Ian Devlin


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();
like image 43
LPunker Avatar answered Oct 16 '22 15:10

LPunker