react-use-audio
TypeScript icon, indicating that this package has built-in type declarations

0.1.5 • Public • Published

react-use-audio

A React Hook for Easily Handle Sound

  • ⭐️ With Typescript
  • 🚀 Declarative Hooks API
  • 🛠 Using Audio Web API

You can easily play, pause, and stop sounds with React Hooks.

Installation

using yarn

yarn add react-use-audio

using NPM

npm install react-use-audio

Usage

Play sound with onClick Event

import { useAudio } from "react-use-audio";

// You need to add sound-related files
import testSound from "../sounds/test.mp3";

function App() {
  const { play } = useAudio(testSound);

  return <button onClick={play}>start</button>;
}

export default App;

Play, Pause, Stop sound with onClick Event

import { useAudio } from "react-use-audio";

// You need to add sound-related files
import testSound from "../sounds/test.mp3";

function App() {
  const { play, stop, pause } = useAudio(testSound);

  return (
    <>
      <button onClick={play}>start</button>
      <button onClick={pause}>pause</button>
      <button onClick={stop}>stop</button>
    </>
  );
}

export default App;

Check if the sound is paused or playing

import { useAudio } from "react-use-audio";

// You need to add sound-related files
import testSound from "../sounds/test.mp3";

function App() {
  const { data, play, stop, pause } = useAudio(testSound);

  return (
    <>
      <button onClick={play}>start</button>
      <button onClick={pause}>pause</button>
      <button onClick={stop}>stop</button>
      <div>is pause: {data.isPause ? "true" : "false"}</div>
      <div>is play: {data.isPlaying ? "true" : "false"}</div>
    </>
  );
}

export default App;

If the path to mp3 is not found in CRA and typescript environment

Add audio.d.ts under the src directory and add the code below.

declare module "*.mp3";
declare module "*.wav";

Package Sidebar

Install

npm i react-use-audio

Weekly Downloads

5

Version

0.1.5

License

MIT

Unpacked Size

13.5 kB

Total Files

8

Last publish

Collaborators

  • takhyun_kim