Skip to content

Commit

Permalink
refactor: use Web Audio API instead
Browse files Browse the repository at this point in the history
  • Loading branch information
fivestar committed Jun 23, 2024
1 parent 3b6156c commit 56b9f7d
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions app/src/Timer/TimerApp.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { useInterval } from 'usehooks-ts'
import "./Timer.css";
import { TimeField } from './TimeField';
Expand All @@ -12,6 +12,8 @@ export default function TimerApp() {
const [seconds, setSeconds] = useState<number>(5 * 60);
const [delay, setDelay] = useState<number | null>(null);
const [isRunning, setIsRunning] = useState<boolean>(false);
const audioContextRef = useRef<AudioContext | null>(null);
const audioBufferRef = useRef<AudioBuffer | null>(null);

useInterval(() => {
setSeconds(seconds - 1);
Expand All @@ -27,6 +29,17 @@ export default function TimerApp() {
setDelay(isRunning ? INTERVAL : null);
}, [isRunning])

useEffect(() => {
audioContextRef.current = new AudioContext();
fetch('/assets/app/assets/audio/dora.m4a')
.then(response => response.arrayBuffer())
.then(arrayBuffer => audioContextRef.current?.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
audioBufferRef.current = audioBuffer || null;
})
.catch(err => console.error('Error loading audio file', err));
}, []);

const handleStart = () => {
try {
const seconds = toSeconds(inputTime);
Expand Down Expand Up @@ -56,9 +69,12 @@ export default function TimerApp() {
};

const playGong = () => {
const audio = new Audio('/assets/app/assets/audio/dora.m4a');
audio.volume = 1.0;
audio.play();
if (audioBufferRef.current && audioContextRef.current) {
const source = audioContextRef.current.createBufferSource();
source.buffer = audioBufferRef.current;
source.connect(audioContextRef.current.destination);
source.start(0);
}
};

const controlDisabled = !isValidTimeString(inputTime)
Expand Down

0 comments on commit 56b9f7d

Please sign in to comment.