d296725 Jan 31, 2018
1 contributor

Users who have contributed to this file

112 lines (85 sloc) 3.03 KB


FaCC that creates an <audio> element to play audio tracks, re-renders on audio state changes.


import {Audio} from 'libreact/lib/Audio';

<Audio autoPlay src=''>{(control, state) => {
  JSON.stringify(state, null, 4)


In addition to props below also accepts all React's media events.

interface IAudioProps {
  src: string;
  autoPlay?: boolean;
  loop?: boolean;
  muted?: boolean;
  preload?: 'none' | 'metadata' | 'auto';
  volume?: number;
  noJs?: React.ReactElement<any>;
  • src - required, string, audio source file URL.
  • autoPlay - optional, boolean, whether to autoplay audio, defaults to false.
  • loop - optional, boolean, whether to repeat the track when it ends, defaults to false.
  • muted - optional, boolean, whether to mute the audio, defaults to false.
  • preload - optional, string, <audio> element preload attribute.
  • volume - optional, number, audio volume in [0..1] range, defaults to 1.
  • noJs - optional, React element(s) to render insided the <audio> tag.
  • onMount - optional, callback, called when component mounts, receives IAudio as the first argument.
  • onUnmount - optional, callback, called when component un-mounts, receives IAudio as the first argument.


The children function receives two arguments, audio instance as controller and state.

<Audio autoPlay src={src}>{(audio, state) =>


First argument is the <Audio> component instance with the following public signature.

interface IAudio {
  el: HTMLAudioElement;
  seek(time: number);
  volume(value: number);

, where

  • el - <audio> element DOM node.

The second argument is the state of the <Audio> component with the following signature.

interface IAudioState {
  time?: number;
  duration?: number;
  isPlaying?: boolean;
  muted?: boolean;
  volume?: number;

, where

  • time - current time in seconds.
  • duration - total audio track duration in seconds.
  • isPlaying - whether the audio track is currently playing.
  • muted - whether muted attribute is set on the audio element.
  • volume - current volume in range [0..1].


Play a sample audio track with control buttons.

<Audio src=''>
  {({play, pause, seek, volume, mute, unmute}, state) =>
      <button onClick={play}>Play</button>
      <button onClick={pause}>Pause</button>
      <button onClick={() => seek(state.time - 5)}>Seek -</button>
      <button onClick={() => seek(state.time + 5)}>Seek +</button>
      <button onClick={() => volume(state.volume - 0.05)}>Volume -</button>
      <button onClick={() => volume(state.volume + 0.05)}>Volume +</button>
      <button onClick={mute}>Mute</button>
      <button onClick={unmute}>Unmute</button>