U
U
uRoot2021-01-12 11:04:48
React
uRoot, 2021-01-12 11:04:48

How to organize work with sounds in React?

In a large React project, audio is played on different occasions: when elements are clicked or when the page loads. This is what I did and it works. But when everything was already completed, when a scheme for working with sound was developed, a new task flew in:

When you click on the button, you need to turn off the sound for all audio, both for the one playing in the background and for clicking, and if the component is updated and new events appear, during which audio is played , then they must also be silent.

And I have a problem with this. I don't know how to re-package the sound scheme so that I can accomplish this task. Now it works like this:

There are small functions that play only one audio:

export const musicHouse = () => {
  audioCore(
    `/assets/sounds/music_house.ogg`,
    true,
  );
};

If we need this sound, then we hang it on a click, for example. The audioCore function itself is just a set of if-ok: you need to loop - passed true, like that.
The audio itself in the function is played like this:
new Audio(sound)
audio.play()
Need background audio? You are welcome:
componentDidMount() {
        ambBase()
}


Tell me how you can organize work with sound so that the audio played during an event or after loading the page I can calmly stir up, and the new audio that may appear when updating the component is already without sound. Provided that the call functions can be located anywhere, in heaps of different components, the calls of some generally lie in json, which is steamed in the component.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kovalsky, 2021-01-12
@uroot

Just make the isMuted flag, depending on which Audio instances will either play sound or not. Where exactly to push this flag depends on the architecture and your preferences. HTMLMediaElement has a muted property , you can drop this flag directly there, it seems like a good plan

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question