DEV Community

sbin
sbin

Posted on

Introducing the React Audio Wizard: A Headless Audio Player for Your React Applications

Managing audio playback in your React applications just got a whole lot easier! We're thrilled to introduce react-audio-wizard, a headless audio player custom-built for React.

This unique library is designed as a hook, providing you the flexibility to play audio files, pause, seek, and track both the current time and duration of the audio. The best part? It's incredibly simple to implement.

Getting Started with React Audio Wizard

To start using react-audio-wizard, install it via npm or yarn:

npm install react-audio-wizard // or yarn
Enter fullscreen mode Exit fullscreen mode

You can check out a live demo of the hook in action over at CodeSandbox.

Integrating React Audio Wizard Into Your Application

The real magic of react-audio-wizard lies in its simplicity. Here's a quick look at how you can leverage it in your application:

import { useAudioWizard } from 'react-audio-wizard'

function MyComponent() {
  const { status, play, pause, handleSeek, duration, currentTime } = useAudioWizard({ url: 'audiofile.mp3' })

  return (
    <div>
      <button onClick={play} disabled={status !== 'loaded' && status !== 'paused'}>
        Play
      </button>
      <button onClick={pause} disabled={status !== 'playing'}>
        Pause
      </button>
      <button onClick={() => handleSeek({ seekTime: 1 })}>+1</button>
      <p>Status: {status}</p>
      <p>Duration: {duration}</p>
      <p>Current Time: {currentTime}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Understanding the API

The useAudioWizard function accepts a single argument: an object containing the URL of the audio file you'd like to play.

This function returns an object packed with useful properties:

status: Provides the current status of the audio. It can return 'idle', 'loaded', 'playing', or 'paused'.
play: A function that starts the audio playback.
pause: A function that pauses the audio.
handleSeek: A function that seeks the audio to a specific time. This function accepts an object with a seekTime property.
duration: Returns the total duration of the audio in seconds.
currentTime: Returns the current playback position in seconds.
The status property is particularly interesting as it provides real-time updates on the state of the audio player. The possible values are:

'idle': The player is initialized but has not started loading any audio data yet.
'loaded': The audio data is fully loaded and ready for playback.
'playing': The audio is currently playing.
'paused': The audio is paused.
With the MIT License, react-audio-wizard is ready for your next project. Whether you're looking to add a unique soundscape to your website or build an immersive audio experience for your users, react-audio-wizard is up to the task! So why wait? Start experimenting with audio in your React apps today!

Top comments (0)