如何为网页嵌入的embed音频应用JavaScript实现随机起始播放?
Hey there! The core issue here is that the <embed> element is a legacy plugin-based tag—it doesn't expose the same media API properties (like duration or currentTime) that the standard <audio> element provides. That’s exactly why your code works for <audio> but falls flat with <embed>.
Let’s fix this properly, while also addressing Chrome’s strict auto-play policy (the reason you turned to <embed> in the first place). Here’s a modern, reliable solution:
Revised Code Using Standard <audio> Element
<body> <audio id="audio" src="berlin.mp3" loop muted></audio> <script> window.addEventListener('load', function() { const audio = document.getElementById('audio'); // Wait for audio metadata to load so we can access its duration audio.addEventListener('loadedmetadata', function() { const audioDuration = audio.duration; if (!isNaN(audioDuration)) { // Set random start time between 0 and the full audio length audio.currentTime = Math.random() * audioDuration; // Attempt auto-play, handle Chrome's policy restrictions audio.play().catch(error => { console.log('Auto-play blocked by browser policy:', error); // Add a manual play button as a fallback const playButton = document.createElement('button'); playButton.textContent = 'Start Background Audio'; playButton.style.cssText = 'position: fixed; top: 20px; right: 20px; padding: 8px 16px;'; playButton.addEventListener('click', () => { audio.play(); playButton.remove(); }); document.body.appendChild(playButton); }); } }); }); </script> </body>
Why This Works
<audio>Element: It’s fully supported across all modern browsers and gives you complete control over playback via the Media API (includingcurrentTimeandduration).- Chrome Auto-Play Bypass: The
mutedattribute lets us auto-play silently, which Chrome allows. If you need audio with sound, you can add a user interaction listener (like a page click) to setaudio.muted = false;after playback starts. - Metadata Wait: We listen for the
loadedmetadataevent to ensure we only set the start time once the audio’s duration is available—this avoidsNaNerrors that happen if we try to accessdurationtoo early. - Fallback Button: If auto-play is still blocked (rare, but possible), users can manually start the audio with a button.
Why <embed> Isn’t a Good Option
If you’re set on sticking with <embed>, I have bad news: there’s no cross-browser reliable way to control its playback position. Plugin support for <embed> is inconsistent, and most modern browsers limit or ignore API access to plugin-based media. Switching to <audio> is the only sustainable approach here.
内容的提问来源于stack exchange,提问作者luckylou

