react-use-audio-player

repository·main·Indexed 43 days ago

https://github.com/e-kuerschner/useaudioplayer

A React library for enhanced control over audio playback in web applications. It provides the useAudioPlayer hook for local audio state and an AudioPlayerProvider with useAudioPlayerContext for sharing a single audio source across multiple components. Features include support for Web Audio API and HTML5 Audio streaming, playback state management (isLoading, isReady), and an escape hatch to access the underlying Howl instance from Howler.js.

Tokens
6.8K
Snippets
21
Records
27
Agent score
55%

What's inside react-use-audio-player

  1. How useAudioPlayerContext and AudioPlayerProvider work together

    main

    When you need to control a single audio source across many different components in your application, use the Context API pattern provided by this library.

    1. Wrap your component tree (or a specific subtree) with the AudioPlayerProvider component.
    2. Use the useAudioPlayerContext hook in any child component to access the shared AudioPlayer instance.

    This ensures all components share the same audio source, state, and API methods.

    // App.tsx
    function App() {
        return (
            <AudioPlayerProvider>
                <PlayPauseButton />
                <VolumeControl />
            </AudioPlayerProvider>
        )
    }
    
    // PlayPauseButton.tsx
    function PlayPauseButton() {
        const { togglePlayPause, isPlaying } = useAudioPlayerContext()
        return (
            <button onClick={togglePlayPause}>
                {isPlaying ? "Pause" : "Play"}
            </button>
        )
    }
  2. Access the underlying Howl instance via the player escape hatch

    main

    The useAudioPlayer hook provides an idiomatic React interface, but it does not expose every feature of the underlying Howler.js library (such as spatial audio or sprites). To access these features, use the player object returned by the hook. This object is the raw Howl instance.

    Warning: Performing operations directly on the player instance may cause the React hook's internal state to desynchronize from the actual audio state.

    const { player } = useAudioPlayer()
    
    player.once("seek", () => {
        console.log("I just seeked!")
    })
  3. Handle pending audio states

    main

    Use the isLoading, isReady, or isUnloaded properties returned by useAudioPlayer to manage UI states while audio is being prepared. For example, you can show a loading spinner while isLoading is true and disable playback controls until isReady is true.

    const { isReady, isLoading, togglePlayPause } = useAudioPlayer("/mySong.wav", {
        autoplay: true
    })
    
    return isLoading ? (
        <LoadingSpinner />
    ) : (
        <PlayButton disabled={!isReady} onClick={togglePlayPause} />
    )
  4. Configure eslint-plugin-react

    main

    To use React-specific linting rules, install eslint-plugin-react and update your eslint.config.js. You must specify the React version in settings and include the recommended rules and jsx-runtime rules in the rules object.

    // eslint.config.js
    import react from 'eslint-plugin-react'
    
    export default tseslint.config({
      // Set the react version
      settings: { react: { version: '18.3' } },
      plugins: {
        // Add the react plugin
        react,
      },
      rules: {
        // other rules...
        // Enable its recommended rules
        ...react.configs.recommended.rules,
        ...react.configs['jsx-runtime'].rules,
      },
    })
  5. Install react-use-audio-player

    main

    You can install the react-use-audio-player package using either yarn or npm. This package provides React developers with tools to control sound in web applications.

    yarn add react-use-audio-player
    
    # or
    
    npm install react-use-audio-player
  6. Stream large audio files using HTML5 Audio

    main

    By default, the underlying engine uses the Web Audio API, which requires downloading the entire file before playback. To stream large files or audio from an API, you must force the use of an HTML5 <audio> element by setting html5: true in the load function options. If your source URL does not include a file extension, you must also specify the format (e.g., mp3).

    const { load } = useAudioPlayer()
    
    load("https://stream.toohotradio.net/128", {
        autoplay: true,
        html5: true,
        format: "mp3"
    })
  7. Configure type-aware ESLint rules for production

    main

    To enable type-aware linting in a production application using tseslint, you must configure the parserOptions to point to your TypeScript configuration files and upgrade your recommended rule sets. This allows ESLint to use type information for more accurate linting.

    export default tseslint.config({
      languageOptions: {
        // other options...
        parserOptions: {
          project: ['./tsconfig.node.json', './tsconfig.app.json'],
          tsconfigRootDir: import.meta.dirname,
        },
      },
    })
  8. Run the demo applications

    main

    To run the example applications located in the demos directory, you must first build the core package locally.

    1. Complete the Monorepo Setup steps.
    2. Build the react-use-audio-player package using yarn g:build-package.
    3. Navigate to a specific demo workspace and run yarn start, or use the workspace command from the root.
    # Build the core package
    yarn g:build-package
    
    # Option 1: Run from within a demo directory
    cd demos/[DEMO_FOLDER]
    yarn start
    
    # Option 2: Run from the monorepo root
    yarn workspace [NAME_OF_DEMO_FOLDER] start