Created
November 23, 2022 04:39
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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