|
- import * as childProcess from 'child_process';
- import { unlinkSync, readFileSync } from 'fs';
-
- export enum VideoType {
- YOUTUBE = 'youtube',
- }
-
- interface ClipVideoBaseParams {
- url: string,
- start: number | string,
- end: number | string,
- ffmpegExecutablePath?: string;
- }
-
- interface ClipYouTubeVideoParams extends ClipVideoBaseParams {
- downloaderExecutablePath?: string;
- }
-
- interface ClipVideoParams extends ClipYouTubeVideoParams {
- type: VideoType,
- }
-
- const clipYouTubeVideo = (params: ClipYouTubeVideoParams) => {
- if (!params.downloaderExecutablePath) {
- throw new Error('Downloader not found.');
- }
- if (!params.ffmpegExecutablePath) {
- throw new Error('ffmpeg not found.');
- }
- childProcess.spawnSync(params.downloaderExecutablePath, [params.url, '-o', 'input.webm']);
- childProcess.spawnSync(params.ffmpegExecutablePath, ['-ss', params.start.toString(), '-t', params.end.toString(), '-i', 'input.webm', 'output.webm']);
- unlinkSync('input.webm');
- const output = readFileSync('output.webm');
- unlinkSync('output.webm');
- return output;
- };
-
- export const clipVideo = (params: ClipVideoParams) => {
- const {
- type: videoType, url, start, end,
- } = params;
-
- switch (videoType as string) {
- case VideoType.YOUTUBE:
- return clipYouTubeVideo({
- ffmpegExecutablePath: process.env.FFMPEG_EXECUTABLE_PATH,
- downloaderExecutablePath: process.env.YOUTUBE_DOWNLOADER_EXECUTABLE_PATH,
- url,
- start,
- end,
- });
- default:
- break;
- }
-
- throw new TypeError(`Invalid video type: "${videoType}". Valid values are: ${JSON.stringify(Object.values(VideoType))}`);
- };
|