Youtube iframe on ionic app generate play icon background

Viewed 248

I'm developing an app, using Ionic 3, thats reproduce a youtube video. As I want an embedded video I use an iframe where the src is the video's url. When I test on an Android device, i get this before the video starts playing.

video after playin on android device

Is there a way to avoid that background? or make it personalized? Testing it using "ionic serve" makes the background completely black, so it only happens running on an android device.

2 Answers

Why not use a temporary <img>, as soon as the user clicks on the img, the <iframe> tag is toggled on, with Autoplay = true.

I recommend using angular youtube-player. You can detect when the video is ready to play. If the video is not ready yet, just display an image or a spinner.

Here is an example:

HTML:

<img class="video-loading-cover" src="assets/images/home/ytcover.png" height="550" width="1400" [hidden]="isVideoLoaded" alt="">

<youtube-player #youTubePlayer (ready)="playVideo($event)" (stateChange)="onPlayerStateChange($event)" (error)="hideVideo()"
                  width="100%" height="540px" [playerVars]="playerVars" [videoId]="videoId"></youtube-player>

TS:

    @ViewChild('youTubePlayer') youTubePlayer: YT.Player;
      isVideoLoaded: boolean;
      videoId = 'your video id';

      // optional
      playerVars: YT.PlayerVars = {
        autoplay: AutoPlay.AutoPlay,
        loop: Loop.Loop,
        playlist: 'yourPlaylist',
        controls: Controls.Hide,
        enablejsapi: JsApi.Enable,
        origin: window.location.origin,
        rel: RelatedVideos.Hide,
        iv_load_policy: IvLoadPolicy.Hide,
        autohide: AutoHide.HideAllControls,
        showinfo: ShowInfo.Hide
      };

  ngOnInit() {
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    document.body.appendChild(tag);
  }

onPlayerStateChange(el) {
    this.youTubePlayer.mute();
    switch (el.data) {
      case -1:
      case 2:
        this.youTubePlayer.playVideo();
        break;
      case 1:
        this.isVideoLoaded = true;
        break;
    }
  }

  hideVideo(): void {
    this.isVideoLoaded = false;
  }

  playVideo(event): void {
    this.youTubePlayer.mute();
    setTimeout(() => {
      this.youTubePlayer.playVideo();
    }, 10);
  }

Note that in my example when the youtube video is loading it will call the (error)="hideVideo()" function and an image will be displayed. When it is available it will automatically hide the image and play the video.

Related