Skip to main content

Advanced Usage


There are two main ways to use this package, and combining both methods offers a third approach:

  1. <Audio /> function as children
  2. The useAudio hook
  3. The combined approach

1. <Audio /> function as children

Passing a function as React children to the <Audio /> component :

// AudioPlayer.tsx

import { Audio } from '@sina_byn/re-audio';

const AudioPlayer = () => {
return (
<Audio
playlist={[
{ id: 1, src: '/audio/1.mp3', name: 'for-her-chill' },
{ id: 2, src: '/audio/2.mp3', name: 'trap-type-beat-rap-instrumental-riff' },
{ id: 3, src: '/audio/3.mp3', name: 'whip-afro-dancehall' },
]}
>
{audioContext => (
<>
<button type='button'>{audioContext.playing ? 'pause' : 'play'}</button>
</>
)}
</Audio>
);
};

export default AudioPlayer;

2. The useAudio hook

Using the context provided by the <Audio /> component via the useAudio hook :

// PlaybackControls.tsx

import { useAudio } from '@sina_byn/re-audio';

const PlaybackControls = () => {
const { playing, togglePlay, prevTrack, nextTrack, rewindTrack, forwardTrack } = useAudio();

return (
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
<button type='button' onClick={rewindTrack.bind(null, 10)}>
rewind
</button>

<button type='button' onClick={prevTrack}>
prev
</button>

<button type='button' onClick={togglePlay}>
{playing ? 'pause' : 'play'}
</button>

<button type='button' onClick={nextTrack}>
next
</button>

<button type='button' onClick={forwardTrack.bind(null, 10)}>
forward
</button>
</div>
);
};

export default PlaybackControls;
// AudioPlayer.tsx

import { Audio } from '@sina_byn/re-audio';

// * components
import PlaybackControls from './PlaybackControls';

const AudioPlayer = () => {
return (
<Audio
playlist={[
{ id: 1, src: '/audio/1.mp3', name: 'for-her-chill' },
{ id: 2, src: '/audio/2.mp3', name: 'trap-type-beat-rap-instrumental-riff' },
{ id: 3, src: '/audio/3.mp3', name: 'whip-afro-dancehall' },
]}
>
<PlaybackControls />
</Audio>
);
};

export default AudioPlayer;

3. The combined approach

To have the best of both worlds, feel free to do:

// AudioPlayer.tsx

import { Audio, formatTime } from '@sina_byn/re-audio';

// * components
import PlaybackControls from './PlaybackControls';

const AudioPlayer = () => {
return (
<Audio
playlist={[
{ id: 1, src: '/audio/1.mp3', name: 'for-her-chill' },
{ id: 2, src: '/audio/2.mp3', name: 'trap-type-beat-rap-instrumental-riff' },
{ id: 3, src: '/audio/3.mp3', name: 'whip-afro-dancehall' },
]}
>
{audioContext => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
<span>{formatTime(audioContext.currentTime)}</span>
<PlaybackControls />
</div>
)}
</Audio>
);
};

export default AudioPlayer;