# React Native Audio Player (Pro)

> A React Native audio player for podcasts and music on iOS, Android and the web: a track card with artwork, a waveform scrubber from your peaks with the played part filled, skip back 15 and forward 30, playback speed, previous and next, a mini player bar that keeps playing while people browse, and an episode list with a now-playing indicator. HTMLAudioElement on the web; expo-audio through one adapter. Part of Patine Pro.

# AudioPlayer Pro

The pieces of a podcast or music app. `AudioPlayer` is the track card: artwork, title and show, a waveform you scrub with the played part filled, skip back 15 and forward 30 seconds, speed (1×, 1.25×, 1.5×, 2×, 0.75×), and previous and next in a playlist. `MiniPlayer` is the bar that keeps playing at the bottom of the screen while people browse. `TrackList` is the list of episodes or songs, with bars bouncing on the one that's playing.

All three read one player from `useAudioPlayer`, so pressing play in one updates the others. The web plays through an `HTMLAudioElement`; on iOS and Android you pass an `adapter` built on expo-audio ([below](#ios-and-android-with-expo-audio)).

```tsx
import { AudioPlayer, MiniPlayer, TrackList, useAudioPlayer } from '@patine-ui/pro';
```

```tsx live
import { AudioPlayer } from '@patine-ui/pro';

// Your server measures the peaks once (audiowaveform, ffmpeg, or the Web Audio API) and sends them with the episode.
const wave = (seed) =>
  Array.from({ length: 240 }, (_, i) => {
    const phrase = Math.abs(Math.sin(i / 9 + seed)) * 0.7 + 0.3;
    const syllable = Math.abs(Math.sin(i * 1.7 + seed * 3)) * 0.6 + 0.4;
    return (i % 31 > 28 ? 0.12 : phrase * syllable);
  });

const EPISODE = {
  id: 'ep-39',
  src: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
  title: 'Designing calm software',
  artist: 'Build Notes',
  meta: 'Episode 39 · Nov 15 · 6 min',
  artwork: 'https://images.unsplash.com/photo-1478737270239-2f02b77fc618?w=400&q=70',
  duration: 372,
  peaks: wave(1),
};

export default function Example() {
  return <AudioPlayer track={EPISODE} style={{ width: '100%', maxWidth: 640 }} />;
}
```

Under 520 points wide the card stacks: the artwork beside the title, the waveform below, and the controls centred.

## Example: a podcast app

One `useAudioPlayer` drives everything. `TrackList` loads and plays the episode you press (pressing the playing one pauses it); `onEnded` moves to the next; the card's previous and next walk the list; and the `MiniPlayer` stays at the bottom with the same state.

```tsx live
import { VStack } from 'patine-ui';
import { AudioPlayer, MiniPlayer, TrackList, useAudioPlayer } from '@patine-ui/pro';

const wave = (seed) =>
  Array.from({ length: 240 }, (_, i) => (i % 29 > 26 ? 0.1 : (Math.abs(Math.sin(i / 8 + seed)) * 0.7 + 0.3) * (Math.abs(Math.sin(i * 1.3 + seed)) * 0.6 + 0.4)));
const art = (id) => `https://images.unsplash.com/photo-${id}?w=300&q=70`;

const EPISODES = [
  { title: 'Designing calm software', art: '1478737270239-2f02b77fc618', minutes: 372, date: 'Nov 15' },
  { title: 'The cost of a context switch', art: '1590602847861-f357a9332bbc', minutes: 425, date: 'Nov 8' },
  { title: 'Shipping on Fridays', art: '1589903308904-1010c2294adc', minutes: 343, date: 'Nov 1' },
  { title: 'Interfaces that age well', art: '1511379938547-c1f69419868d', minutes: 302, date: 'Oct 25' },
].map((e, i) => ({
  id: `ep-${39 - i}`,
  src: `https://www.soundhelix.com/examples/mp3/SoundHelix-Song-${i + 1}.mp3`,
  title: e.title,
  artist: 'Build Notes',
  meta: `Ep. ${39 - i} · ${e.date}`,
  artwork: art(e.art),
  duration: e.minutes,
  peaks: wave(i + 1),
}));

export default function Podcast() {
  const step = (by) => {
    const index = EPISODES.findIndex((e) => e.id === player.track?.id);
    const next = EPISODES[index + by];
    if (next) player.load(next);
  };
  const player = useAudioPlayer({ track: EPISODES[0], onEnded: () => step(1) });
  return (
    <VStack gap="md" style={{ width: '100%', maxWidth: 640 }}>
      <AudioPlayer player={player} onPrevious={() => step(-1)} onNext={() => step(1)} />
      <TrackList tracks={EPISODES} player={player} />
      <MiniPlayer player={player} onPress={() => {}} />
    </VStack>
  );
}
```

In an app, put the `MiniPlayer` above the tab bar in your root layout and open the full `AudioPlayer` in a sheet from its `onPress`.

## Compact

`variant="compact"` is one row (play, title, waveform, time) for a voice note, a lesson clip or a preview in a feed.

```tsx live
import { VStack } from 'patine-ui';
import { AudioPlayer } from '@patine-ui/pro';

const wave = (n) => Array.from({ length: 120 }, (_, i) => 0.2 + 0.8 * Math.abs(Math.sin(i / 5 + n) * Math.cos(i / 13)));

export default function Example() {
  return (
    <VStack gap="sm" style={{ width: '100%', maxWidth: 420 }}>
      <AudioPlayer variant="compact" track={{ id: 'a', title: 'Lesson 3 · Listening', src: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3', duration: 343, peaks: wave(1) }} />
      <AudioPlayer variant="compact" track={{ id: 'b', title: 'Voice memo from Maya', src: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3', duration: 302 }} />
    </VStack>
  );
}
```

Without `peaks` the scrubber is a plain bar.

## An album

`numbered` shows track numbers in place of artwork, with the bars on the playing one.

```tsx live
import { TrackList, useAudioPlayer } from '@patine-ui/pro';

const TRACKS = ['Opening', 'Late trains', 'Field notes', 'Small hours'].map((title, i) => ({
  id: `t${i}`,
  title,
  artist: 'SoundHelix',
  src: `https://www.soundhelix.com/examples/mp3/SoundHelix-Song-${i + 5}.mp3`,
  duration: [354, 297, 401, 322][i],
}));

export default function Album() {
  const player = useAudioPlayer();
  return <TrackList tracks={TRACKS} player={player} numbered style={{ width: '100%', maxWidth: 480 }} />;
}
```

## iOS and Android with expo-audio

The `adapter` gets a source and `emit`, starts a native player, and returns the controls for it:

```tsx
import { createAudioPlayer, setAudioModeAsync } from 'expo-audio';

await setAudioModeAsync({ playsInSilentMode: true, shouldPlayInBackground: true });

export const expoAudio = (src, emit) => {
  const player = createAudioPlayer(src, { updateInterval: 100 });
  const sub = player.addListener('playbackStatusUpdate', (s) =>
    emit({
      playing: s.playing,
      currentTime: s.currentTime,
      duration: s.duration,
      waiting: s.isBuffering,
      ended: s.didJustFinish,
      started: s.playing || s.currentTime > 0,
    })
  );
  return {
    play: () => player.play(),
    pause: () => player.pause(),
    seek: (t) => player.seekTo(t),
    setRate: (r) => player.setPlaybackRate(r),
    setVolume: (v) => (player.volume = v),
    setMuted: (m) => (player.muted = m),
    release: () => {
      sub.remove();
      player.remove();
    },
  };
};

const player = useAudioPlayer({ track, adapter: expoAudio });
```

For lock-screen controls, call expo-audio's `setActiveForLockScreen` with the track's title and artwork in the same adapter.

## Accessibility

- Play and pause, skip ("Back 15 seconds"), speed ("Playback speed: 1.5×"), previous and next are named buttons, 44pt or larger.
- The waveform is a slider: screen readers read "2 minutes 5 seconds of 6 minutes 12 seconds" and step with increment and decrement; on the web it takes focus.
- `TrackList` rows read title, show and length, and say "Now playing" on the current one (`aria-current`). The bouncing bars are hidden from screen readers and still with reduce motion on.

## Props

### useAudioPlayer

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `track` | `AudioTrack` | — | The first track. |
| `autoPlay` | `boolean` | `false` | Play it as soon as it loads. |
| `adapter` | `(src, emit) => MediaController` | — | Plays on iOS and Android. |
| `rates` | `number[]` | `[1, 1.25, 1.5, 2, 0.75]` | Speeds the speed button cycles through. |
| `onEnded` | `(track) => void` | — | A track finished: load the next. |

It returns `{ track, state, load(track, { autoPlay }), play, pause, toggle, seek, seekBy, setRate, cycleRate }`. `state` has `playing`, `currentTime`, `duration`, `buffered`, `rate`, `waiting`, `ended`, `error`.

`AudioTrack` is `{ id, src, title, artist?, artwork?, duration?, peaks?, meta? }`; `peaks` are 0 to 1, any count (they're resampled to fit).

### AudioPlayer

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `player` | `AudioPlayerController` | — | A shared player from `useAudioPlayer`. |
| `track` | `AudioTrack` | — | Without `player`, a track for a player of its own. |
| `variant` | `'card' \| 'compact'` | `'card'` | The card, or one row. |
| `skipBack`, `skipForward` | `number` | `15`, `30` | Seconds the skip buttons jump. |
| `onPrevious`, `onNext` | `() => void` | — | Show previous and next buttons. |
| `labels`, `style`, `theme`, `design` | | | |

### MiniPlayer

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `player` | `AudioPlayerController` | **required** | The shared player. Draws nothing until it has a track. |
| `onPress` | `() => void` | — | Open the full player. |
| `onClose` | `() => void` | — | Show a close button. |
| `skipForward` | `number` | `30` | Seconds its skip button jumps. |
| `labels`, `style`, `theme`, `design` | | | |

### TrackList

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `tracks` | `AudioTrack[]` | **required** | The episodes or songs. |
| `player` | `AudioPlayerController` | **required** | Marks its track; a press plays or pauses. |
| `numbered` | `boolean` | `false` | Numbers in place of artwork. |
| `labels`, `style`, `theme`, `design` | | | |

## Related

- [Video player](./video-player): the same controls for video.
- [Messenger](../blocks/messenger): voice messages in a chat.
