I am trying to play/show a video Advertisement(just a h1 tag) at each index value in the array. For example; the first item in the array is 5. So at 5 seconds, I want the video to pause and play an ad. Then again at 10 seconds, then at 15. Assume the currentTime variable increments from 0 seconds to the end of the video. How can I trigger each ad to play when the currentTime value matches one of the adstream array index values?
let adStream: string;
let currentTime = 0;
let showAd: boolean = false;
let adStartTimes: Array<number> = [5, 10, 15]; //How to trigger on each value in array???
let storedStreamTime: number;
let storedProgress: number;
//Manually setting first index of array, but really want to check for matching index???
$: if (Math.round(currentTime) === adStartTimes[0]) {
//Pause the original video...
videoElement && videoElement.pause();
//Store the original progress and time...
storedStreamTime = Math.round(currentTime);
storedProgress = Math.round((currentTime / duration!) * 100);
//Switch to the ad video, this should be the URI eventually, just a string for now...
adStream = 'Ad Playing';
//Show overlayed ad video...
showAd = true;
}
//play the ad if showing...
$: if (showAd) {
playDummyAd();
}
const playDummyAd = () => {
//after 5 second ad is done...
setTimeout(() => {
console.log('ad played');
showAd = false;
//return to current video time...
currentTime = storedStreamTime + 1;
progress = storedProgress + 1;
//resume play of original video...
videoElement.play();
}, 5000);
};
{#if showAd}
<h1 class="p-4 text-white bg-red-500">{adStream}</h1>
{/if}
2
Answers
According to my understanding I have modified some javascript code for check if currentTime match value inside the array of adStartTimes
Like this below code :-
and playDummyAd function should accept the time
Like this below code :-
Checking if the currentTime matches one of the
adStartTimes
values can be achieved with a reactive statement (since the user might seek, this should be independent of the index)When there’s currently an ad played (probably unlikely, but still one of the
adStartTimes
might overlap with the length of an ad) or when the user is seeking over one of the start values, the playback should be preventedREPL