Skip to content

Instantly share code, notes, and snippets.

@drpshtiwan
Created November 23, 2022 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drpshtiwan/45fd233695b168056af980c56b93579c to your computer and use it in GitHub Desktop.
Save drpshtiwan/45fd233695b168056af980c56b93579c to your computer and use it in GitHub Desktop.
<?php
// Needs PHP-FFMpeg
namespace App\Helpers;
use FFMpeg\Coordinate\TimeCode;
class DurationHelper
{
private int|float $seconds;
private int $splitDuration;
public array $intervals;
public array $segments;
public function __construct(int|float $seconds, int $splitDuration)
{
$this->seconds = $seconds;
$this->splitDuration = $splitDuration;
$this->setIntervals();
$this->setSegments();
}
public static function segments(int|float $seconds): array
{
return (new self($seconds))->segments;
}
public static function intervals(int|float $seconds): array
{
return (new self($seconds))->intervals;
}
private function setSegments(): void
{
foreach(range(1, $this->intervals['whole']) as $index => $value) {
$this->segments[] = $this->segmentItem( $this->startingPoint($index), $this->splitDuration);
}
$this->insertLastSegment();
}
public function insertLastSegment(): void
{
if (0 !== $this->intervals['fractionSeconds']) {
$this->segments[] = $this->segmentItem( $this->endingPoint(), $this->intervals['fractionSeconds']);
}
}
private function setIntervals(): void
{
$totalSeconds = (int) $this->seconds;
$segments = $totalSeconds / $this->splitDuration;
$whole = (int) $segments;
$wholeSeconds = $whole * $this->splitDuration;
$fraction = $segments - $whole;
$fractionSeconds = $totalSeconds - $wholeSeconds;
$this->intervals = [
'whole' => $whole,
'fraction' => $fraction,
'totalSeconds' => $totalSeconds,
'wholeSeconds' => $wholeSeconds,
'fractionSeconds' => $fractionSeconds,
];
}
private function startingPoint(int $segment): string
{
return $segment * $this->splitDuration;
}
private function endingPoint(): string
{
return $this->intervals['totalSeconds'] - $this->intervals['fractionSeconds'];
}
private function segmentItem(int $start, int $duration)
{
return [
'start' => (string) TimeCode::fromSeconds($start),
'duration' => (string) TimeCode::fromSeconds($duration)
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment