Javascript javascript音频加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8256915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:21:12  来源:igfitidea点击:

javascript audio onload

javascripthtmlaudio

提问by Uw001

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

我做了一个 javascript 音频测试。所有功能都适用于 Opera FF 和 Chrome,除了 audio.oncanplaythrough 和 audio.onended(这 2 个功能不适用于 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>

回答by Ian Devlin

oncanplaythroughis an event, not a method, and the other event is called endedand not onended.

oncanplaythrough是一个事件,而不是一个方法,另一个事件被调用ended而不是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);

回答by LPunker

Add and play a sound via JavaScript

通过 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_acidHyman_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

在歌曲中精确播放 35 秒

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