iTranslated by AI
Playing Simple Sound Effects in the Browser Without Libraries
There are often cases where you want to play a short sound effect (SE) in the browser.
Nowadays, it can be done sufficiently with AudioContext and OscillatorNode, so I'm taking a note of it here.
Note that this method may produce slight noise; for more professional results, it is better to use Tone.js.
Demo
Explanation
Basics of AudioContext + OscillatorNode
The part for playing sound is roughly like this. You should be able to confirm that it works in the debug console with something like the following.
const audioCtx = new window.AudioContext();
const oscillator = audioCtx.createOscillator();
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(1200, audioCtx.currentTime);
oscillator.connect(audioCtx.destination);
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + 0.5);
Preparing for sound processing by outputting a short silence
In modern browsers, the Audio API cannot be used without user interaction like a click event.
To work around this, we can insert a component that outputs a moment of silence.
const SoundReady: FC<PropsWithChildren<{}>> = ({ children }) => {
const [ready, setReady] = useState(false)
// Play silence.
const playReadySound = (onPlayEnd: () => void) => {
const audioCtx = new window.AudioContext()
const oscillator = audioCtx.createOscillator()
oscillator.type = 'triangle'
oscillator.frequency.setValueAtTime(0, audioCtx.currentTime)
oscillator.connect(audioCtx.destination)
oscillator.onended = () => {
onPlayEnd()
}
oscillator.start(0)
oscillator.stop(0)
}
const onSetup = () => {
playReadySound(() => {
setReady(true)
})
}
if (!ready) {
return <Button onClick={() => onSetup()}>
Setup
</Button>
}
return <>{children}</>
}
Making a "Pipo" Sound
From here on, we'll build the part that plays sounds in response to events.
To create a sound like the "pipo" heard when a battery is running low, you can change the frequency over time as follows:
const onPress = () => {
const audioCtx = new window.AudioContext()
const oscillator = audioCtx.createOscillator()
oscillator.type = 'sine'
oscillator.frequency.setValueAtTime(1200, audioCtx.currentTime)
oscillator.frequency.setValueAtTime(800, audioCtx.currentTime + 0.1)
oscillator.connect(audioCtx.destination)
oscillator.start(audioCtx.currentTime)
oscillator.stop(audioCtx.currentTime + 0.2)
}
Making a "Pipi" Sound
For a "pipi" sound like electronic money, creating two nodes and setting them up as follows will make it sound just like it.
const onPress = () => {
const audioCtx = new window.AudioContext()
const nodes = [
audioCtx.createOscillator(),
audioCtx.createOscillator()
]
const hz = 1700
nodes.map(node => {
node.type = 'sine'
node.frequency.setValueAtTime(hz, audioCtx.currentTime)
node.connect(audioCtx.destination)
})
const length = 0.1
const rest = 0.025
nodes[0].start(audioCtx.currentTime)
nodes[0].stop(audioCtx.currentTime + length)
nodes[1].start(audioCtx.currentTime + length + rest)
nodes[1].stop(audioCtx.currentTime + length * 2 + rest)
}
A Button that Sounds While Held Down
Lastly, a button that makes a "buuu" sound while it is being pressed. For this, we need to separate the start and stop actions, so we will use useRef this time.
const SoundBoo = () => {
const audioCtxRef = useRef<AudioContext>()
const oscillatorRef = useRef<OscillatorNode>()
useEffect(() => {
audioCtxRef.current = new AudioContext()
}, [])
const start = () => {
if (!audioCtxRef.current || oscillatorRef.current) {
return
}
const audioCtx = audioCtxRef.current
const oscillator = audioCtx.createOscillator()
oscillator.type = 'sawtooth'
oscillator.frequency.setValueAtTime(100, audioCtx.currentTime)
oscillator.connect(audioCtx.destination)
oscillatorRef.current = oscillator
oscillator.start(audioCtx.currentTime)
}
const stop = () => {
if (!audioCtxRef.current) {
return
}
oscillatorRef.current?.stop(audioCtxRef.current.currentTime)
oscillatorRef.current?.disconnect()
oscillatorRef.current = undefined
}
return <Stack>
<Button
onMouseDown={() => start()}
onMouseUp={() => stop()}
onMouseOut={() => stop()}
colorScheme={"red"} variant="outline">
ブー ❌
</Button>
</Stack>
}
If we only use onMouseUp, the sound will keep playing if the mouse moves out while being held down, so we should also attach it to onMouseOut.
Discussion