最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - javascript audio onload - Stack Overflow

programmeradmin2浏览0评论

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(".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>

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>
Share Improve this question asked Nov 24, 2011 at 12:16 Uw001Uw001 3631 gold badge5 silver badges12 bronze badges 1
  • 1 This question has nothing to do with onload? Please change title accordingly. – DarkTrick Commented Dec 23, 2021 at 10:49
Add a comment  | 

2 Answers 2

Reset to default 22

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

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();
发布评论

评论列表(0)

  1. 暂无评论