Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Web Audio API only playing when code changes?

So I have this code to load in an audio file and play it:

export function Note(props) {

const [played, setPlayed] = useState(false);
    const noteDiv = useRef();
    const play = useRef();
    const [isPlaying, setIsPlaying] = useState(false);

const note = useRef();
    const audioContext = useRef(new (window.AudioContext || window.webkitAudioContext)());

// gets the file as an Audio Buffer

    useEffect(() => {
        fetch(props.filePath)
        .then(data => {
            // console log goes here
            return data.arrayBuffer();
         })
        .then(arrayBuffer => {
            const decode = audioContext.current.decodeAudioData(arrayBuffer);
            return decode;
        })
        .then(decodedAudio => {
            note.current = decodedAudio;
        });
    }, []);

    const playNote = async () => {
        if (audioContext.state === "suspended") {
            await audioContext.current.resume();
        }
        const play = audioContext.current.createBufferSource();
        play.buffer = note.current;
        play.connect(audioContext.current.destination);
        play.start();
    };

// This component constantly renders as its state changes constantly while the playhead moves

useEffect(() => { 
        setPlayed(isPlayed(props.progress));
    }, [props.progress]);

    useEffect(() => {
        if (played) {
            playNote();
        } else {
            stopNote();
        }
    }, [played]);

return (
    <div></div>
);



}

Basically, a playhead moves across the screen, and when a note is underneath it, the note plays an audio file.

For some reason, when I run the code and the playhead starts moving, no sound is heard even though the play.start() is called.

But, if I change something in the code, it works for some reason. For example, if I add a console log where I indicated and go back to my browser, the sound plays.

Is this because the Note component is rerendering? Why isn't just having the play.start() call itself not playing anything?

The filepath is correct and I can see that a file is loaded, and that an AudioBufferSourcenode is created with it. It's just the start() method that isn't working.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!