How do I set a fixed audio volume upon loading React.js page, using useSound?

344 Views Asked by At

My code:

 import React from 'react';
 import useSound from 'use-sound';
 import music from '../audio/cny music.mp3';

 const Audio = () => {
 const [play] = useSound(music,{ volume:0.2  });
 return (
     <audio onload={ play}></audio>
   );      
 };

 export default Audio

My audio plays upon loading page, however, the volume is still at max even though i set it at 0.2. Am i missing out on something?

1

There are 1 best solutions below

0
MarcM On

Try this:

import { useState, useEffect } from 'react';
import useSound from 'use-sound';

const MyComponent = () => {
  const [play, { stop }] = useSound('path/to/audio.mp3', { volume: 0.2 });

  useEffect(() => {
    play();
  }, []);

  return (
    // your component's JSX
  );
}

You can also adjust the volume after the sound has been played by using the stop function returned by the useSound hook, which allows you to stop the sound and apply new options to it, including the volume.

stop();
play({ volume: newVolume });