【问题标题】:Replaying an Audio element in chrome在 chrome 中重放音频元素
【发布时间】:2014-03-02 02:03:35
【问题描述】:
sounds["foo"]= new Audio("foo.ogg");
function playSound(id){

var snd = this.sounds[id];

if(snd.currentTime>snd.duration*0.99999){
    snd.pause();
    snd.currentTime=0;
    //snd.seekable.start(); //doesnt work
    //snd.load(); does the trick but with the cost re-downloading the clip every single time
    snd.play();
}
if(snd.currentTime==0)
snd.play();
}

出于某种原因 playSound('foo');第一次工作,但在 Chrome 上失败(在 Firefox 上工作得很好)。添加 snd.load() 似乎可以解决此问题,但现在每次播放剪辑时它都会从服务器下载剪辑,这在我的用例中很多。

编辑:哦,snd.currentTime 似乎最后卡住了,所以 snd.currentTime=0 什么都不做。

【问题讨论】:

    标签: javascript html google-chrome audio


    【解决方案1】:

    以下脚本适用于我在 OSX、Chrome 版本 32.0.1700.102 和 Firefox 27.0 上。

    如果您不想立即循环文件,那么您的脚本绝对是正确的方法。

    我无法重现您的问题。我将该方法与链接上的 onclick 操作相关联,并使用 5s .ogg 文件进行测试。单击链接并重新播放音频文件一直对我有用。 我注意到的唯一可能的问题是您的第二个 if 子句。如果第一个 if 匹配,则时间设置为 0 并播放文件。即使在我看来这不太可能,也可能是第二个 if 也匹配并且 snd.play() 被第二次调用。因此我会使用 else if。

    你可以试一试吗?即使我认为它不能解决您的问题:/

    <script type="text/javascript">
        var sounds = [];
        sounds["foo"]= new Audio("foo.ogg");
    
        /* First solution, creating a loop */
        function playSoundLoop(id){
            var snd = this.sounds[id];  
            snd.play();
            snd.addEventListener('ended', function(){
                this.currentTime = 0;
                this.play();
                }, false);
        }
    
        /* Use else if instead of if */
        function playSound(id){
            var snd = this.sounds[id];
    
            if(snd.currentTime>snd.duration*0.99999){
                snd.pause();
                snd.currentTime=0;
                snd.play();
            } else if(snd.currentTime==0) {
                snd.play();
            }
        }
    </script>
    

    【讨论】:

    • 我不想循环播放声音,而是希望能够再次播放声音而无需从服务器重新加载。
    • @user1185421 很抱歉。我更新了答案并提到了其他一些事情。
    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2018-03-25
    • 2016-05-02
    • 2014-07-16
    相关资源
    最近更新 更多