angulartypescriptyoutubeplayer

how can I change the startSeconds of Youtube dynamically in Angular


what I expected is that whenever the startSeconds property of youtube-player changes, the youtube-player would jump to the new startSeconds. However, although I had changed the variable bound to startSeconds property, the youtube video didn't play from the startSeconds I just set.

may I know if it is viable viable way or there is another method to reach what I anticipated?

Thanks

 <youtube-player 
  [videoId]="videoId" 
  suggestedQuality="highres" 
  [height]="250" 
  [width]="500" 
  [startSeconds]="timeStamp">
</youtube-player>

Solution

  • startSeconds is an @Input so you should be able to bind to it.

    <youtube-player [startSeconds]="30"></youtube-player>
    

    However, while the latest value from the binding is used, it's only considered if the player has been created and hasn't started playing.

    const cueOptionsObs = combineLatest([startSecondsObs, endSecondsObs]).pipe(
      map(([startSeconds, endSeconds]) => ({startSeconds, endSeconds})),
    );
    
    // Only respond to changes in cue options if the player is not running.
    const filteredCueOptions = cueOptionsObs.pipe(
      filterOnOther(playerObs, player => !!player && !hasPlayerStarted(player)),
    );
    

    The player is considered to have started playing if it's in any state except UNSTARTED or CUED.

    function hasPlayerStarted(player: YT.Player): boolean {
      const state = player.getPlayerState();
      return state !== YT.PlayerState.UNSTARTED && state !== YT.PlayerState.CUED;
    }
    

    So you cannot change the binding of startSeconds to make the player jump. You might be able to change the playbackState to CUED by calling stopVideo(), after which you should be able to change the value of startSeconds before calling startVideo() to start at your new position.

    stopVideo() {
      if (this._player) {
        this._player.stopVideo();
      } else {
        // It seems like YouTube sets the player to CUED when it's stopped.
        this._getPendingState().playbackState = YT.PlayerState.CUED
      }
    }