Images, video & sound
Image, Video, and Audio layers from local or remote files.
Image, Video, and Audio read files through src. Relative paths start from the composition file, so keep media beside it in your project folder.
src can also be an http:// or https:// URL. Native preview, export, and preloadMedia() download it into a local cache on first use. Later runs reuse the cached file without revalidation; use a new URL or clear the cache when its content changes. A download fails when any step before the response (looking up the domain, connecting, sending the request, or receiving the response headers) takes more than 30 seconds, or when its data stops arriving for 30 seconds; a large file that keeps arriving is never cut off, however long it takes. A URL whose download failed is not requested again for 30 seconds, so a missing or unreachable file does not slow down every preview frame; after that, it is tried again. As in a browser, the URL is normalized before the download: spaces and non-ASCII characters in the path and query are percent-encoded, a non-ASCII domain is written in its ASCII (punycode) form, and the #fragment is left out. A URL that differs only in this way, or in the case of its scheme and domain, uses the same cached file.
import { Audio, Composition, Image, Sequence, Video, frameKeyframes } from '@celesta.studio/react';
import { mediaDurationInFrames, preloadMedia } from '@celesta.studio/media-utils';
const FPS = 30;
let clipFrames = 150;
// Runs once before the first frame: read the clip's length from the file.
export async function prepare() {
const clip = await preloadMedia('./media/walk.mp4');
clipFrames = mediaDurationInFrames(clip, FPS) ?? clipFrames;
}
export default function Root() {
return (
<Composition width={1920} height={1080} fps={FPS}
durationInFrames={clipFrames + 60}>
<Sequence durationInFrames={clipFrames}>
<Video src="./media/walk.mp4" />
</Sequence>
<Sequence from={clipFrames}>
<Image src="./media/end-card.png" />
</Sequence>
{/* Fade the music in over the first two seconds. */}
<Audio
src="./media/music.wav"
volume={frameKeyframes([
{ frame: 0, value: 0 },
{ frame: 60, value: 0.8, easing: 'ease-out' },
], { fps: FPS })}
/>
</Composition>
);
}
- An
ImageorVideois drawn at its own pixel size unless you give itwidthorheight. One of them alone keeps the picture's proportions; with both, aVideois stretched to that box, and anImageis too unlessfit="contain"fits it inside the box or"cover"fills the box, cropping what spills over. Position it withx/yand anchors;scaleand aFitresize it as they do any layer. Images can be PNG, JPEG, WebP, GIF, or PNM. - An animated GIF, APNG, or WebP plays on the enclosing sequence's clock, each frame for its own delay, and loops.
startFromandplaybackRatework as onVideo;loop={false}holds the last frame.preloadMedia()reports its length asanimation.durationSeconds. VideoandAudioacceptstartFrom(seconds into the file),playbackRate,volume, andmuted. AVideoplays its own soundtrack, so do not add anAudiowith the same file to hear it; setmutedto keep only the picture.loopon aVideoorAudiostarts the file over from its beginning when playback reaches its end, picture and sound together, instead of holding the last frame in silence.- Media placed inside a
Sequencestarts when the sequence does and stops when it ends. volumeand an audioplaybackRatecan be a number or keyframes. Keyframe times are seconds from the start of the enclosing sequence, written as{ value, timescale }.- Each of these props, when set, must be a finite number, or keyframes whose times and values are all finite. A
NaN, such as a volume computed from a misspelled field, throws an error that names the component and the prop instead of playing at the default.
frameKeyframes(keys, { fps, origin? }) builds volume, playbackRate, or pitch keyframes from frame numbers. Times are (frame - origin) / fps on the enclosing sequence’s clock; origin defaults to 0. Use it for volume changes that a fade does not cover, such as lowering music under a voice. The browser exporter supports keyframed volume and playback rate, but not pitch.
Show media in a frame
MediaFrame from @celesta.studio/components fits an image or a video into a frame of a given width and height, drawn by Panel (background, border over the media, rounded corners, shadow, and a padding mat), with an optional caption under it. kind ("image" or "video") says which the media is; it is never guessed from the file name. fit="contain" (the default) shows all of it, centred; "cover" fills the frame, cropped. A Video has no fit, so MediaFrame scales a video to fit itself and needs its size as sourceWidth and sourceHeight: read them once with preloadMedia() in prepare(). startFrom, playbackRate, volume, muted, and loop reach the Video unchanged, so it starts with its Sequence and sounds as a bare Video would. Only the plain frame exists for now.
let clip: MediaInfo;
export async function prepare() { clip = await preloadMedia("./demo.mp4"); }
<MediaFrame kind="video" src={clip.src} sourceWidth={clip.video!.width} sourceHeight={clip.video!.height}
width={960} height={540} fit="cover" cornerRadius={24} caption="App preview" />
Fade in and out
fadeIn and fadeOut take seconds. The clip rises from silence over the first fadeIn seconds it is heard and falls back to silence over the last fadeOut seconds.
<Sequence durationInFrames={300}>
<Audio src="bgm.mp3" volume={0.6} fadeIn={1.5} fadeOut={3} />
</Sequence>
- The fades are timed from where the clip starts and stops being heard: the edges of its
Sequence, or of an outer one that cuts it shorter. When the sequence gets longer or shorter, the fade-out moves with its end. - Each fade multiplies
volume, whether it is a number or keyframes. The fades do not replace it. - The fades are linear in amplitude. No other curve is available yet.
- When
fadeInandfadeOutadd up to more than the clip, they overlap and multiply, so the clip never reaches full volume. - The fades are timed on the timeline, not on the file:
loopdoes not repeat them, andplaybackRateandpitchdo not stretch them. When the file ends before the clip does, the fade-out falls after the sound has stopped. - Only
Audiotakes these props, and in a project JSON file anaudioitem takes them as times. The soundtrack of aVideoand the voices of aDialoguedo not. A negative value is an error. The browser exporter applies them too.
Turn music down under voices
duckGroup puts a clip in a group, and duck turns a clip down while a clip of the groups it names plays. Dialogue voices are in the group "voice" already, so BGM under a dialogue needs only duck.
<Audio src="bgm.mp3" volume={0.6} duck={{ under: 'voice' }} />
<Video src="game.mp4" duck={{ under: 'voice', to: { db: -12 }, release: 0.8 }} />
tois the gain under the voices, as a multiplier from 0 to 1 or as{ db }at or below 0. It defaults to 0.3 and multipliesvolumeand the fades.attackis how many seconds the gain takes to come down, ending as the voice starts (0.15 by default).releaseis how many it takes to come back up after the voice ends (0.4 by default). With 0, the gain switches instantly, which can click on some material.- Silences shorter than
holdGapseconds (0.6 by default) stay ducked, so the music does not bob up between lines. - A voice counts from its start until its file runs out or its
Sequenceends, whichever comes first, so a subtitle held after the voice does not keep the music down. A looping voice counts for its whole sequence. Muted clips do not count. - Preview, export, and the browser exporter play the same curve. In a project JSON file,
audioandvideoitems takeduckGroupandduck, anddialogueitems takeduckGroup.
Change the pitch
By default an Audio's pitch follows its speed, like tape: playbackRate={1.25} is faster and higher. Two props separate them.
<Audio src="bgm.mp3" playbackRate={1.25} preservePitch pitch={-2} />
pitchtransposes the clip in semitones. It defaults to 0 and ranges from −24 to 24; a fraction is cents, so0.5is 50 cents. It can be a number or keyframes, built withframeKeyframeslikevolume. Outside the range, the React path clamps to ±24 and a project JSON file fails validation.preservePitchdefaults tofalse:playbackRatechanges speed and pitch together, as before. Whentrue,playbackRatechanges only how long the clip takes, andpitchalone sets the pitch.- The pitch you hear is multiplied by
2^(pitch / 12), timesplaybackRateunlesspreservePitchis set.pitch={12}is one octave up. - Only
Audiotakes these props. The soundtrack of aVideoand the voices of aDialoguedo not. The preview and the export sound the same, but the browser exporter in@celesta.studio/webrejects a clip that uses them, with the error "Audio pitch and preservePitch are not supported by browser export yet."
Sound effects without files
For ticks, pops, whooshes, and simple music, write the sound as data instead of placing files: @celesta-plugin/score records them against the composition's frames, seconds, and beats, renders them to a WAV in prepare(), and plays it through an <Audio>, the same bytes every run.
Size a scene to its media
The optional prepare() export runs once before rendering and may be async. In the example, preloadMedia() reads the clip’s length and mediaDurationInFrames() converts it to frames, so the end card always follows the footage.
Move with the sound
loadAudioSpectrum() decodes an audio file, or a video’s soundtrack, in prepare() and analyzes all of it. useAudioSpectrum() then returns the current frame’s frequency bands and loudness, so bars, rings, and glows can follow the music or a voice.
import { Audio, Composition, Rect } from '@celesta.studio/react';
import { loadAudioSpectrum, useAudioSpectrum } from '@celesta.studio/media-utils';
import type { AudioSpectrum } from '@celesta.studio/media-utils';
let music: AudioSpectrum;
// Decode and analyze the whole file once, before the first frame.
export async function prepare() {
music = await loadAudioSpectrum('./media/music.wav', {
bands: 24,
smoothing: { attack: 0.01, release: 0.2 },
});
}
function Bars() {
// This frame's band levels (0–1) and loudness.
const { bands, rms } = useAudioSpectrum(music);
return (
<>
{bands.map((level, band) => (
<Rect key={band} x={160 + band * 66} y={900} width={50}
height={8 + level * 600} anchorY={1} fill="#4e62bc" />
))}
<Rect x={960} y={180} width={200 + rms * 1200} height={24}
anchorX={0.5} fill="#f55138" />
</>
);
}
export default function Root() {
return (
<Composition width={1920} height={1080} fps={30} durationInFrames={300}>
<Bars />
<Audio src={music.src!} />
</Composition>
);
}
bandslists every band from low to high frequency, each from 0 to 1. A band’s level is its mean FFT power in dB, relative to a full-scale sine, mapped fromminDecibels(default −80) tomaxDecibels.maxDecibelsdefaults to'auto', the loudest band level anywhere in the file, so only the loudest moments reach 1 however loud the file was mastered. Pass a number, such asmaxDecibels: -6, for a fixed ceiling, for example to give several files the same scale.rmsis the root mean square of the samples, about 0.707 for a full-scale sine.fftSizesets the samples in each FFT (a power of two, default 2048).bandssets the number of bands (default 32), andscalehow the range fromminFrequency(20 Hz) tomaxFrequency(16 kHz) is divided:'log'(the default) gives each octave the same number of bands,'linear'the same width in Hz, and'mel'follows perceived pitch.smoothingtakes seconds, or{ attack, release }for rising and falling values separately: after that long a value has made about 63% of a change. The default 0 follows the sound exactly.- The file is analyzed once, in order, every
hopSeconds(1/240 s by default), with a Hann window centered on each moment, and frames read between two analyses interpolate them. The value of a frame therefore does not depend on the fps or on the order frames are rendered in, and is the same in the preview and in the export. - The hook follows the enclosing
Sequence’s clock, likeAudio. PassstartFromwhen theAudiohas one.playbackRateis not followed. Before and after the file every value is 0. spectrumAt(spectrum, seconds)returns the same values outside a component, andanalyzeAudioSpectrum({ sampleRate, samples }, options)analyzes samples you already have.- The channels are averaged, and the file is analyzed at its own sample rate. Relative paths and URLs resolve as for
preloadMedia().