As read in many forums, using built-in looping in VideoPlayer doesn’t work well as there is a short audio break before the video restarts. I’ve tried many solutions… but no way. In the end I’ve tried to adapt a solution found in [StackOverflow][1] according to my needs:
using System.Collections;
using UnityEngine;
using UnityEngine.Video;
public class MegaPlayer : MonoBehaviour
{
private VideoPlayer[] players = new VideoPlayer[2];
public RenderTexture targetTexture;
public string url;
void Awake()
{
for (int i = 0; i < players.Length; i++) {
players *= gameObject.AddComponent<VideoPlayer>();*
players*.source = VideoSource.Url;*
players*.url = url;*
players*.playOnAwake = false;*
players*.waitForFirstFrame = true;*
players*.isLooping = false;*
players*.skipOnDrop = true;*
players*.targetTexture = targetTexture;*
}
}
void Start()
{
StartCoroutine(Play(0));
}
IEnumerator Play(int activePlayer)
{
// wait until the video is ready
players[activePlayer].Prepare();
while (!players[activePlayer].isPrepared) {
yield return null;
}
players[activePlayer].Play();
// wait until the current video has not finished
bool reachedHalfWay = false;
int nextPlayer = activePlayer ^ 1;
while (players[activePlayer].isPlaying) {
if (!reachedHalfWay && players[activePlayer].time >= (players[activePlayer].length / 2)) {;
reachedHalfWay = true;
players[nextPlayer].time = 0f;
players[nextPlayer].Prepare();
}
yield return null;
}
while (!players[nextPlayer].isPrepared) {
yield return null;
}
StartCoroutine(Play(nextPlayer));
}
}
The idea is to simulate isLooping
by creating 2 VideoPlayer
instances that alternate each other. When one play is half the way, I start preparing the second one so that it is ready before the current play ends.
The problem is that the result is a pure mess. It looks like both players start together anyway. Does anybody have a better idea on how to implement a seamless video looping?
_*[1]: c# - Play different videos back to back seamlessly using Unity Video Player - Stack Overflow