在Codepen测试JS音频播放:为何once1可多次播放once2仅能一次?
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 (withloopset tofalse), itscurrentTimeproperty typically stays at the end of the track by default. Some browsers won't restart playback viaplay()unless you manually resetcurrentTimeto0first.For
birdSound, it’s likely either:- The audio file’s metadata triggers the browser to automatically reset
currentTimeto0after playback ends, or - The server hosting this file uses headers that let the browser reload/replay the audio without extra hurdles.
- The audio file’s metadata triggers the browser to automatically reset
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 modifyonce2to reset the playback position before callingplay(), it’ll work repeatedly:function once2(){ simple.currentTime = 0; simple.play(); };Quick way to verify
Check thecurrentTimevalue of both audio elements after they finish playing. You’ll almost certainly seesimple.currentTimestuck at the track’s total duration, whilebirdSound.currentTimeresets to0automatically.
内容的提问来源于stack exchange,提问作者PeterT

