react-tone 🎶
A React component that plays a tone from an oscillator.
Getting started
npm install --save react-tone
Why?
react-tone
is a component that uses a OscillatorNode to play a sound at a given frequency
and length
.
You can pass react-tone
an instance of AudioContext. This solves an issue playing sounds on iOS devices. On iOS devices, a sound is muted until it's created from an interaction event. Using an AudioContext to play a dummy buffer fixes this. See this issue for more information.
API
Props | Description | Default |
---|---|---|
play | (Boolean) Play a tone | false |
length | (Number) How long the tone should play (in seconds) | 0.05 |
frequency | (Number) The frequency of the tone | 400 |
volume | (Number) The volume of the tone (0 being silent, and 1 being the loudest) | 1 |
audioContext | (Object) An instance of AudioContext | new AudioContext() |
onStop | (Function) Callback function to be called when the tone has finished playing | () => {} |
import React Component from "react";import Tone from "react-tone"; { ; thisstate = isTonePlaying: false ; thisaudioContext = undefined; thisiosAudioContextUnlocked = false; } { thisaudioContext = ; } { if !thisiosAudioContextUnlocked this; this; } { // start an empty buffer with an instance of AudioContext const buffer = thisaudioContext; const node = thisaudioContext; nodebuffer = buffer; node; thisiosAudioContextUnlocked = true; } { this; } { // Pass the same instance of AudioContext that played an empty buffer to <Tone /> return <div> <button =>Play Tone</button> <Tone = = = = = = /> </div> ; }
Demo
See this CodeSandbox demo.