Cod Fish
Cod Fish

Reputation: 947

Switch the video file for the HTML5 video tag in run-time smoothly

I'm working on an Angular [4+] application. In one of my HTML templates I have a HTML5 video tag.

I have n files located on the disk:

1.mp4

2.mp4

...

n-1.mp4

n.mp4

Once the user pressed the Play button, I want the video to start playing the first file:

1.mp4

Once the file ends, I want the same HTML video tag to start playing the file:

2.mp4

and so on till it reaches the n.mp4 and play it to it's end.

I want that the switching of the files would be as smooth as possible, with no latency, no loading time, as if the HTML video tag plays a single file without switching n files.

The only solution I have in mind is changing the src attribute of the HTML video tag, and maybe implement some buffer so that if the x.mp4 is about to reach it's end, the x+1 file already starts loading. Any ideas on how to implement this?

What do you think is the ideal solution for this scenario? (Note that combining those n files into one in advance is not an option, cause those files are created dynamically, and I know the exact amount of files only once the user has pressed play on the HTML video tag).

Upvotes: 1

Views: 1865

Answers (2)

Suryan
Suryan

Reputation: 659

You can try to use ended event on video

Note: Not tested, it could be in the comment but I think it would be too long for the comment

In your template add following code

<video #video width="256" height="192"  id="myVideo" controls autoplay>
 <source #source src="{{count}}.mp4" id="mp4Source" type="video/mp4">
 Your browser does not support the video tag.
</video>

import ViewChild, ElementRef, Renderer2 from '@angular/core' in your component and in ngAfterViewInit lifecycle hook

count = 1;
@ViewChild('video') video: ElementRef;
@ViewChild('source') source: ElementRef;

constructor(private rd: Renderer2){}

ngAfterViewInit() {
 let player = this.video.nativeElement;
 let mp4Vid = this.source.nativeElement;
 this.rd.listen(player, 'ended', (event) => {
  if(!event) {
    event = window.event;
  }

 this.count++;
 this.rd.setAttribute(mp4Vid, 'src', `${this.count}.mp4`)
 player.load();
 player.play();
  })
}

Hope this might help you and for further reference ended event for video

Upvotes: 1

Orit
Orit

Reputation: 343

You can try to use the [hidden] attribute on the videos, you can check if it buffers the video. Once one video is done you can set the video to hidden = true and the next video to hidden = false. And use the autoplay = true in order to play it without having the user click on play.

Upvotes: 0

Related Questions