You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Codepen测试JS音频播放:为何once1可多次播放once2仅能一次?

Why does one Audio play function work multiple times while the other only works once?

I tested the following code snippets in Codepen and found that the once1 function can play the audio multiple times freely, while the once2 function can only play it once. Can anyone explain the difference between the two?

The Code:

var simple = new Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1(){ birdSound.play(); };
function once2(){ simple.play(); };

Answer

Great question! Let's break down the key differences causing this behavior:

  • Playback state reset behavior
    When an Audio element finishes playing (with loop set to false), its currentTime property typically stays at the end of the track by default. Some browsers won't restart playback via play() unless you manually reset currentTime to 0 first.

    For birdSound, it’s likely either:

    • The audio file’s metadata triggers the browser to automatically reset currentTime to 0 after playback ends, or
    • The server hosting this file uses headers that let the browser reload/replay the audio without extra hurdles.
  • Caching & server policy quirks for simple
    The freeCodeCamp audio file is hosted on S3, which may have stricter caching or cross-origin resource sharing (CORS) policies. These can prevent the browser from reinitializing the playback state after the track finishes. If you modify once2 to reset the playback position before calling play(), it’ll work repeatedly:

    function once2(){ 
      simple.currentTime = 0;
      simple.play(); 
    };
    
  • Quick way to verify
    Check the currentTime value of both audio elements after they finish playing. You’ll almost certainly see simple.currentTime stuck at the track’s total duration, while birdSound.currentTime resets to 0 automatically.


内容的提问来源于stack exchange,提问作者PeterT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:40:32