How to stop music when embedded youtube video star

2019-09-19 14:20发布

I have an HTML site with which music starts on entering, but I want it to stop when the user clicks play on the youtube video that is embedded onto my website.. so it makes the background music and the video music not be able to run simultaneously because that's annoying.

Any idea on how to do that? or if there is any solution for this problem?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-19 15:04

Detect the player's state change (onStateChange event) using JavaScript: https://developers.google.com/youtube/js_api_reference#Events

If the video is loaded using an iframe (as the comments indicate) see Guide for YouTube iframe embeds (note the code sample which detects player events).

Example

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'u1zgFlCw8Aw',
      events: {
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
      // code to stop the audio player should probably go here
    }
  }

When the player starts, use JavaScript to stop the audio. You haven't told us how it is embedded into the page, but nearly any player can be stopped with script (even bgsound can be hacked).

And encourage your client to not auto-play music when the page loads. From a pure business standpoint, it can cost you customers.

查看更多
登录 后发表回答