Capítulo 736 de 988
Extracting frames from a video file, for example to display a filmstrip in an editing interface, can be done using Mediabunny.
type Options = {
track: {width: number; height: number};
container: string;
durationInSeconds: number | null;
};
export type ExtractFramesTimestampsInSecondsFn = (options: Options) => Promise<number[]> | number[];
export type ExtractFramesProps = {
src: string;
timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
onVideoSample: (sample: VideoSample) => void;
signal?: AbortSignal;
};
export async function extractFrames({src, timestampsInSeconds, onVideoSample, signal}: ExtractFramesProps): Promise<void> {
using input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src),
});
const [durationInSeconds, format, videoTrack] = await Promise.all([input.computeDuration(), input.getFormat(), input.getPrimaryVideoTrack()]);
if (!videoTrack) {
throw new Error('No video track found in the input');
}
if (signal?.aborted) {
throw new Error('Aborted');
}
const timestamps =
typeof timestampsInSeconds === 'function'
? await timestampsInSeconds({
track: {
width: videoTrack.displayWidth,
height: videoTrack.displayHeight,
},
container: format.name,
durationInSeconds,
})
: timestampsInSeconds;
if (timestamps.length === 0) {
return;
}
if (signal?.aborted) {
throw new Error('Aborted');
}
const sink = new VideoSampleSink
// ...(truncated)