javascript - 在 Chrome 中重播 Audio 元素

标签 javascript html google-chrome audio

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 什么也不做。

最佳答案

以下脚本在 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>

关于javascript - 在 Chrome 中重播 Audio 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21580668/

相关文章:

javascript - jQuery.data() 和 .data() 之间的区别?

javascript - onclick 方法应用于图像对象导致转换到 "no"页面

php - 如何在 Chrome 上调试 JavaScript

css - Chrome 开发者工具窗口尺寸不一致

javascript - 在鼠标移动到表格单元格上时滚动表格包装器 div。(Chrome)

javascript - 语法错误 : Unexpected token ( for jest

javascript - 如何将用户输入的输入保存为 React 中的数组状态

javascript - 为什么这个 onclick 事件不起作用?

javascript - 独立div js

javascript - 在每个 nt-h 数组元素后插入新元素