简体   繁体   中英

React - Activate sound on render

I manage to activate sound library like

import useSound from 

'use-sound';

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {

const [play] = useSound(boopSfx);

return <button onClick={play}>Boop!</button>;

};

but I would like to make it go off on render part, like to have some if statement and if its satisfied to play it. Any way to do it?

Playing sound on render of button can be achieved using useEffect hook in react. You can see the code here .

const BoopButton = () => {
  const url = "https://www.soundjay.com/button/sounds/beep-01a.mp3";

  const [play] = useSound(url);
  React.useEffect(() => {
    setTimeout(() => {
      play();
    }, 5);
  }, [play]);

  return <button onClick={play}>Boop!</button>;
};

The reason I have added the setTimeOut is to let the URL load so that sound would play, in your case with link to file, it is not needed.

You can use 'useEffect' hook to play the sound just before the component is rendered.

import useSound from 

'use-sound';

import {useEffect} from 'react'

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {

const [play] = useSound(boopSfx);

//keep an empty array to make sure it only executes once
useEffect(()=>play(),[])

return <button onClick={play}>Boop!</button>;

};

It works this way


const [play] = useSound(yourSFX);

useEffect(() => play(), [play])

But make sure that your window is in focus. If it's not, click somewhere inside the window and it will start with the play

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM