预加载音频并在播放期间应用css



我希望创建声音按钮。

在这里使用了答案:按键点击声音

并实现它,以便按钮是div,并从MySQL数据库动态创建。

有人知道如何在页面加载时预加载声音列表吗?

另外,我想应用一个CSS类的div点击时,然后当音频完成时,希望它切换回原来的CSS类。

这是我试过的。声音正常播放,但onended函数没有触发。

    <script type='text/javascript'>
    $(window).load(function(){
    var baseUrl = "http://[URL HERE]";
    var audio = [<?php echo $audiostring; ?>];
    $('div.ci').click(function() {
        var i = $(this).attr('id').substring(1);
        mySound = new Audio(baseUrl + audio[i-1]).play();       
        mySound.onended = function() {
        alert("The audio has ended");};
    });
    });
    </script>

如果你使用的是HTML5音频,你可以这样做:

 mySound.addEventListener("ended", function() 
 {
      alert("The audio has ended");
 });
编辑:

试着改变你创建音频标签的方式,参考这里。

$('div.ci').click(function() {
    var i = $(this).attr('id').substring(1);
    mySound = $(document.createElement('audio'));
    mySound.src = baseUrl + audio[i-1];  
    mySound.play();    
    mySound.addEventListener("ended", function() 
    {
      alert("The audio has ended");
    });
});

<audio>new Audio()应该是相同的,但它看起来没有就像实际情况一样。当我需要创建音频时object中,我创建了一个元素:

ended事件是基于。currenttime属性创建的。event-media-ended

canplaythrough事件用于知道浏览器何时完成音频文件下载,我们可以播放

code complete use close

<style type="text/css">
    body{background: #aaa;color:#fff;}
        div
        {
            width: 100px;
            height: 100px;
            background: #dda;
        }
    </style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
 $(window).load(function(){
    var audioFiles = [
    "http://www.soundjay.com/button/beep-01a.mp3",
    "http://www.soundjay.com/button/beep-02.mp3",
    "http://www.soundjay.com/button/beep-03.mp3",
    "http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
    var audio = new Audio();
    // once this file loads, it will call loadedAudio()
    // the file will be kept by the browser as cache
    audio.addEventListener('canplaythrough', loadedAudio, false);
    audio.src = url;
}
var loaded = 0;
function loadedAudio() {
    // this will be called every time an audio file is loaded
    // we keep track of the loaded files vs the requested files
    loaded++;
    if (loaded == audioFiles.length){
        // all have loaded
        init();
    }
}
var player = document.createElement('audio');
function playAudio(index) {
    player.src = audioFiles[index];
    player.play();
}
function init() {
    $('div').click(function(event) {
        $(this).css('background', 'blue');
        playAudio(Math.floor(Math.random()*audioFiles.length));
        player.addEventListener("ended", function(){
             player.currentTime = 0;
             $(event.target).closest('div').css('background', '#dda');
        });
    });
}
// We begin to upload files array
for (var i in audioFiles) {
    Preload(audioFiles[i]);
}

 });
 </script>

最新更新