Knit UI
GitHub

Media

@knitui/media is one hybrid media kit: the same components, hooks and controller API on web and React Native, with themed chrome that matches the rest of the kit. It ships its own native module for iOS and Android, built on AVFoundation and Media3, so audio and video share one player architecture, one network layer and one audio sampler. On web it drives the browser's own <audio> and <video>.

Setup

npx expo install @knitui/media expo-asset

Add the config plugin to app.json, then rebuild the native app (npx expo prebuild, or a new development build):

{
  "expo": {
    "plugins": [
      [
        "@knitui/media",
        {
          "microphonePermission": "Allow $(PRODUCT_NAME) to access your microphone.",
          "backgroundPlayback": true,
          "pictureInPicture": true
        }
      ]
    ]
  }
}
OptionDefaultWhat it does
microphonePermissiona generic messageiOS microphone prompt text. false leaves the key out.
recordAudioAndroidtrueAdds the Android RECORD_AUDIO permission.
backgroundPlaybacktrueKeeps audio and video playing in the background.
backgroundRecordingfalseKeeps a recording running in the background.
pictureInPicturefalseAllows video Picture in Picture.
import { MediaProvider, AudioPlayer } from "@knitui/media";

<MediaProvider>
  <AudioPlayer source={{ uri }} />
</MediaProvider>;

One control point

MediaProvider is also where audio and video meet. useMediaHub() returns the hub that sits over both, and useMediaState() tells you what is playing.

import { useMediaHub, useMediaState } from "@knitui/media";

function MiniPlayer() {
  const hub = useMediaHub();
  const { focus, audio, video } = useMediaState();
  const playing = focus === "video" ? video?.playing : audio?.playing;

  return <Button onPress={() => hub.togglePlay()}>{playing ? "Pause" : "Play"}</Button>;
}
hub.focus"audio", "video" or null: whichever started playing last.
hub.activeThe controller of the player that has focus.
hub.togglePlay()Play or pause whatever has focus.
hub.pauseAll()Pause audio and video, for a route change or an incoming call.
hub.preload(source)Warm a source of either kind (see below).

Only one thing is heard at a time: when audible playback starts in audio, video pauses, and the other way round. A muted video never takes over, so a silent background clip does not stop the music. To mix the two yourself, turn it off:

<MediaProvider exclusive={false}>

Outside a component, getSharedMediaHub() returns the same hub.

Preloading

Fetch the start of a source before anyone presses play, so the first play starts without a wait:

<Video source={trailer} preload />
<Audio source={episode} preload />

or ahead of time, for a screen that is about to open:

import { preloadMedia } from "@knitui/media";

await preloadMedia("https://cdn.example.com/trailer.mp4");
await preloadMedia(episodeUrl, { kind: "audio", preferredForwardBufferDuration: 20 });

kind is read from the file extension when you leave it out. Preloading is off by default because it spends the visitor's data on media they may never play; turn it on for the one or two players that will be. Each domain also exports preload, clearPreloadedSource, clearAllPreloadedSources and getPreloadedSources.

On iOS and Android a preloaded video is read back from an on-disk cache (HLS is skipped on iOS, whose cache does not cover it). On web it relies on the browser's HTTP cache, so the server has to send cacheable responses.

What is in it

One engine, one player at a time

There is exactly one real player element per medium. That is what makes lock-screen controls, background audio and seamless playlist transitions work — and it means two visible players contend: only the active one plays. If you need a list of tracks, drive one player from the list rather than mounting one per row.

State without re-render storms

Playback state changes many times a second. The store is selector-based and per-field, so a component that reads currentTime re-renders on time updates while one that reads isPlaying does not:

import { useMediaSelector } from "@knitui/media";

const isPlaying = useMediaSelector((state) => state.isPlaying);

Granular events (play, pause, ended, trackChange, …) are derived centrally from state transitions rather than emitted by each adapter, so web and native fire the same events at the same moments.

DSP

@knitui/media/dsp is a pure-TypeScript FFT and spectrum analyser — no native module, no worklet:

import { useAudioSpectrum } from "@knitui/media";

const { bands } = useAudioSpectrum({ bandCount: 32 });

One FFT per frame, fed from a ring buffer. Pair it with @knitui/graphics's AudioVisualizer for the drawing.

Platform notes

Edit this page on GitHub