Skip to main content

@twick/media-utils / Exports

@twick/media-utils

Table of contents

Interfaces

Type Aliases

Functions

Type Aliases

Dimensions

Ƭ Dimensions: Object

Type declaration

NameType
heightnumber
widthnumber

Defined in

types.ts:1


Position

Ƭ Position: Object

Type declaration

NameType
xnumber
ynumber

Defined in

types.ts:3


VideoMeta

Ƭ VideoMeta: Dimensions & { duration: number }

Defined in

types.ts:5

Functions

blobUrlToFile

blobUrlToFile(blobUrl, fileName): Promise<File>

Converts a Blob URL to a File object. Fetches the blob data from the URL and creates a new File object with the specified name. Useful for converting blob URLs back to File objects for upload or processing.

Parameters

NameTypeDescription
blobUrlstringThe Blob URL to convert
fileNamestringThe name to assign to the resulting File object

Returns

Promise<File>

Promise resolving to a File object with the blob data

Example

const file = await blobUrlToFile("blob:http://localhost:3000/abc123", "image.jpg");
// file is now a File object that can be uploaded or processed

Defined in

file-helper.ts:16


detectMediaTypeFromUrl

detectMediaTypeFromUrl(url): Promise<null | "audio" | "video" | "image">

Detects the media type (image, video, or audio) of a given URL by sending a HEAD request. Uses a lightweight HEAD request to fetch only the headers, avoiding download of the full file. The function analyzes the Content-Type header to determine the media type category.

Parameters

NameTypeDescription
urlstringThe URL of the media file to analyze

Returns

Promise<null | "audio" | "video" | "image">

Promise resolving to the detected media type or null

Example

// Detect image type
const type = await detectMediaTypeFromUrl("https://example.com/image.jpg");
// type = "image"

// Detect video type
const type = await detectMediaTypeFromUrl("https://example.com/video.mp4");
// type = "video"

// Detect audio type
const type = await detectMediaTypeFromUrl("https://example.com/audio.mp3");
// type = "audio"

// Invalid or inaccessible URL
const type = await detectMediaTypeFromUrl("https://example.com/invalid");
// type = null

Defined in

url-helper.ts:28


downloadFile

downloadFile(url, filename): Promise<void>

Downloads a file from a given URL and triggers a browser download. Fetches the file content from the provided URL and creates a download link to save it locally. The function handles the entire download process including fetching, blob creation, and cleanup of temporary resources.

Parameters

NameTypeDescription
urlstringThe URL of the file to download
filenamestringThe name of the file to be saved locally

Returns

Promise<void>

Promise resolving when the download is initiated

Example

await downloadFile("https://example.com/image.jpg", "downloaded-image.jpg");
// Browser will automatically download the file with the specified name

Defined in

file-helper.ts:122


extractAudio

extractAudio(«destructured»): Promise<string>

Extracts an audio segment from a media source between start and end times, rendered at the specified playback rate, and returns a Blob URL to an MP3 file. The function fetches the source, decodes the audio track using Web Audio API, renders the segment offline for speed and determinism, encodes it as MP3 using lamejs, and returns an object URL. Callers should revoke the URL when done.

Parameters

NameTypeDefault value
«destructured»Objectundefined
› end?numberundefined
› playbackRate?number1
› srcstringundefined
› start?number0

Returns

Promise<string>

Promise resolving to a Blob URL to the extracted MP3 file

Example

const url = await extractAudio({ src, start: 3, end: 8, playbackRate: 1.25 });
const audio = new Audio(url);
audio.play();
// later: URL.revokeObjectURL(url);

Defined in

audio-utils.ts:32


getAudioDuration

getAudioDuration(audioSrc): Promise<number>

Retrieves the duration (in seconds) of an audio file from a given source URL. Uses a cache to avoid reloading the same audio multiple times for better performance. The function creates a temporary audio element, loads only metadata, and extracts the duration without downloading the entire audio file.

Parameters

NameTypeDescription
audioSrcstringThe source URL of the audio file

Returns

Promise<number>

Promise resolving to the duration of the audio in seconds

Example

// Get duration of an MP3 file
const duration = await getAudioDuration("https://example.com/audio.mp3");
// duration = 180.5 (3 minutes and 0.5 seconds)

// Get duration of a local blob URL
const duration = await getAudioDuration("blob:http://localhost:3000/abc123");
// duration = 45.2

Defined in

get-audio-duration.ts:23


getImageDimensions

getImageDimensions(url): Promise<Dimensions>

Gets the dimensions (width and height) of an image from the given URL. Uses a cache to avoid reloading the image if already fetched, and employs a concurrency limiter to control resource usage and prevent overwhelming the browser with too many simultaneous image loads.

Parameters

NameTypeDescription
urlstringThe URL of the image to analyze

Returns

Promise<Dimensions>

Promise resolving to an object containing width and height

Example

// Get dimensions of a remote image
const dimensions = await getImageDimensions("https://example.com/image.jpg");
// dimensions = { width: 1920, height: 1080 }

// Get dimensions of a local blob URL
const dimensions = await getImageDimensions("blob:http://localhost:3000/abc123");
// dimensions = { width: 800, height: 600 }

// Subsequent calls for the same URL will use cache
const cachedDimensions = await getImageDimensions("https://example.com/image.jpg");
// Returns immediately from cache without reloading

Defined in

get-image-dimensions.ts:53


getObjectFitSize

getObjectFitSize(objectFit, elementSize, containerSize): Dimensions

Calculates the resized dimensions of an element to fit inside a container based on the specified object-fit strategy ("contain", "cover", "fill", or default). Implements CSS object-fit behavior for programmatic dimension calculations. Useful for responsive design and media scaling applications.

Parameters

NameTypeDescription
objectFitstringThe object-fit behavior
elementSizeDimensionsThe original size of the element
containerSizeDimensionsThe size of the container

Returns

Dimensions

Object containing the calculated width and height

Example

// Contain: fit entire element inside container
const contained = getObjectFitSize("contain", {width: 1000, height: 500}, {width: 400, height: 300});
// contained = { width: 400, height: 200 }

// Cover: fill container while maintaining aspect ratio
const covered = getObjectFitSize("cover", {width: 1000, height: 500}, {width: 400, height: 300});
// covered = { width: 600, height: 300 }

// Fill: stretch to completely fill container
const filled = getObjectFitSize("fill", {width: 1000, height: 500}, {width: 400, height: 300});
// filled = { width: 400, height: 300 }

Defined in

dimension-handler.ts:97


getScaledDimensions

getScaledDimensions(width, height, maxWidth, maxHeight): Dimensions

Calculates the scaled dimensions of an element to fit inside a container based on the specified max dimensions while maintaining aspect ratio. Ensures the resulting dimensions are even numbers and fit within the specified bounds. If the original dimensions are already smaller than the max values, returns the original dimensions.

Parameters

NameTypeDescription
widthnumberThe original width of the element in pixels
heightnumberThe original height of the element in pixels
maxWidthnumberThe maximum allowed width of the container in pixels
maxHeightnumberThe maximum allowed height of the container in pixels

Returns

Dimensions

Object containing the calculated width and height

Example

// Scale down a large image to fit in a smaller container
const scaled = getScaledDimensions(1920, 1080, 800, 600);
// scaled = { width: 800, height: 450 }

// Small image that doesn't need scaling
const scaled = getScaledDimensions(400, 300, 800, 600);
// scaled = { width: 400, height: 300 }

// Ensure even dimensions for video encoding
const scaled = getScaledDimensions(1001, 1001, 1000, 1000);
// scaled = { width: 1000, height: 1000 }

Defined in

dimension-handler.ts:30


getThumbnail

getThumbnail(videoUrl, seekTime?, playbackRate?): Promise<string>

Extracts a thumbnail from a video at a specific seek time and playback rate. Creates a hidden video element in the browser, seeks to the specified time, and captures the frame into a canvas, which is then exported as a JPEG data URL or Blob URL. The function handles video loading, seeking, frame capture, and cleanup automatically.

Parameters

NameTypeDefault valueDescription
videoUrlstringundefinedThe URL of the video to extract the thumbnail from
seekTimenumber0.1The time in seconds at which to capture the frame
playbackRatenumber1Playback speed for the video

Returns

Promise<string>

Promise resolving to a thumbnail image URL

Example

// Extract thumbnail at 5 seconds
const thumbnail = await getThumbnail("https://example.com/video.mp4", 5);
// thumbnail is a data URL like "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ..."

// Extract thumbnail with custom playback rate
const thumbnail = await getThumbnail("https://example.com/video.mp4", 2.5, 1.5);

Defined in

get-thumbnail.ts:22


getVideoMeta

getVideoMeta(videoSrc): Promise<VideoMeta>

Fetches metadata (width, height, duration) for a given video source. Uses a cache to avoid reloading the same video multiple times for better performance. The function creates a temporary video element, loads only metadata, and extracts the video properties without downloading the entire file.

Parameters

NameTypeDescription
videoSrcstringThe URL or path to the video file

Returns

Promise<VideoMeta>

Promise resolving to an object containing video metadata

Example

// Get metadata for a video
const metadata = await getVideoMeta("https://example.com/video.mp4");
// metadata = { width: 1920, height: 1080, duration: 120.5 }

// Get metadata for a local blob URL
const metadata = await getVideoMeta("blob:http://localhost:3000/abc123");
// metadata = { width: 1280, height: 720, duration: 30.0 }

Defined in

get-video-metadata.ts:24


limit

limit<T>(fn): Promise<T>

Wraps an async function to enforce concurrency limits. If the concurrency limit is reached, the function is queued and executed later when a slot becomes available. This prevents overwhelming the system with too many concurrent operations, which is useful for resource-intensive tasks like media processing or API calls.

Type parameters

Name
T

Parameters

NameTypeDescription
fn() => Promise<T>Async function returning a Promise that should be executed with concurrency control

Returns

Promise<T>

Promise resolving with the result of the wrapped function

Example

// Limit concurrent image processing operations
const processImage = async (imageUrl) => {
// Expensive image processing operation
return await someImageProcessing(imageUrl);
};

// Process multiple images with concurrency limit
const results = await Promise.all([
limit(() => processImage("image1.jpg")),
limit(() => processImage("image2.jpg")),
limit(() => processImage("image3.jpg")),
limit(() => processImage("image4.jpg")),
limit(() => processImage("image5.jpg")),
limit(() => processImage("image6.jpg")), // This will be queued until a slot opens
]);

Defined in

limit.ts:57


loadFile

loadFile(accept): Promise<File>

Opens a native file picker and resolves with the selected File. The accepted file types can be specified using the same format as the input accept attribute (e.g. "application/json", ".png,.jpg", "image/*").

Parameters

NameTypeDescription
acceptstringThe accept filter string for the file input

Returns

Promise<File>

Promise resolving to the chosen File

Example

const file = await loadFile("application/json");
const text = await file.text();
const data = JSON.parse(text);

Defined in

file-helper.ts:37


saveAsFile

saveAsFile(content, type, name): void

Triggers a download of a file from a string or Blob. Creates a temporary download link and automatically clicks it to initiate the download. The function handles both string content and Blob objects, and automatically cleans up the created object URL after the download is initiated.

Parameters

NameTypeDescription
contentstring | BlobThe content to save, either a string or a Blob object
typestringThe MIME type of the content
namestringThe name of the file to be saved

Returns

void

Example

// Download text content
saveAsFile("Hello World", "text/plain", "hello.txt");

// Download JSON data
saveAsFile(JSON.stringify({data: "value"}), "application/json", "data.json");

// Download blob content
saveAsFile(imageBlob, "image/png", "screenshot.png");

Defined in

file-helper.ts:93


stitchAudio

stitchAudio(segments, totalDuration?): Promise<string>

Stitches multiple audio segments into a single MP3 file. Creates a timeline where each segment plays at its specified time, with silence filling gaps between segments.

Parameters

NameTypeDescription
segmentsAudioSegment[]Array of audio segments with source, start, and end times
totalDuration?numberTotal duration of the output audio

Returns

Promise<string>

Promise resolving to a Blob URL to the stitched MP3 file

Example

const segments = [
{ src: "audio1.mp3", s: 0, e: 5, volume: 1.0 },
{ src: "audio2.mp3", s: 10, e: 15, volume: 0.8 }
];
const url = await stitchAudio(segments, 15);
// Creates a 15-second audio file with segments at specified times

Defined in

audio-utils.ts:95