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

如何为网页嵌入的embed音频应用JavaScript实现随机起始播放?

Fixing Random Start Time for Auto-Playing Audio in Chrome

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 (including currentTime and duration).
  • Chrome Auto-Play Bypass: The muted attribute 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 set audio.muted = false; after playback starts.
  • Metadata Wait: We listen for the loadedmetadata event to ensure we only set the start time once the audio’s duration is available—this avoids NaN errors that happen if we try to access duration too 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:47:07