react-use-audio-player
repository·main·Indexed 43 days ago
https://github.com/e-kuerschner/useaudioplayerA 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.
What's inside react-use-audio-player
- This Remix template comes pre-configured with Tailwind CSS. While Tailwind is provided as a default starting experience, you can use any CSS framework. For more information on handling CSS within this project's build tool, refer to the Vite docs on CSS.
How useAudioPlayerContext and AudioPlayerProvider work together
mainWhen you need to control a single audio source across many different components in your application, use the Context API pattern provided by this library.
- Wrap your component tree (or a specific subtree) with the
AudioPlayerProvidercomponent. - Use the
useAudioPlayerContexthook in any child component to access the sharedAudioPlayerinstance.
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> ) }- Wrap your component tree (or a specific subtree) with the
Access the underlying Howl instance via the player escape hatch
mainThe
useAudioPlayerhook 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 theplayerobject returned by the hook. This object is the rawHowlinstance.Warning: Performing operations directly on the
playerinstance 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!") })Handle pending audio states
mainUse the
isLoading,isReady, orisUnloadedproperties returned byuseAudioPlayerto manage UI states while audio is being prepared. For example, you can show a loading spinner whileisLoadingis true and disable playback controls untilisReadyis true.const { isReady, isLoading, togglePlayPause } = useAudioPlayer("/mySong.wav", { autoplay: true }) return isLoading ? ( <LoadingSpinner /> ) : ( <PlayButton disabled={!isReady} onClick={togglePlayPause} /> )Develop the Remix app
mainTo start the local development server for the Remix application, use thenpm run devcommand.npm run devConfigure eslint-plugin-react
mainTo use React-specific linting rules, install
eslint-plugin-reactand update youreslint.config.js. You must specify the React version insettingsand include the recommended rules andjsx-runtimerules in therulesobject.// 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, }, })Install react-use-audio-player
mainYou can install the
react-use-audio-playerpackage using eitheryarnornpm. 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-playerDeploy the Remix app manually (DIY)
mainThe built-in Remix app server is production-ready for Node.js environments. When deploying manually, ensure you deploy the following output directories generated by
npm run build:build/serverbuild/client
Stream large audio files using HTML5 Audio
mainBy 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 settinghtml5: truein theloadfunction options. If your source URL does not include a file extension, you must also specify theformat(e.g.,mp3).const { load } = useAudioPlayer() load("https://stream.toohotradio.net/128", { autoplay: true, html5: true, format: "mp3" })Configure type-aware ESLint rules for production
mainTo enable type-aware linting in a production application using
tseslint, you must configure theparserOptionsto 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, }, }, })Run the demo applications
mainTo run the example applications located in the
demosdirectory, you must first build the core package locally.- Complete the Monorepo Setup steps.
- Build the
react-use-audio-playerpackage usingyarn g:build-package. - 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] startRun the global-audio Vite Single Page App
mainThe
global-audiopackage is a traditional React Single Page Application (SPA) bundled and served using Vite. To start the development server for this specific workspace, use the following command from the repository root:yarn workspace global-audio start