Roee Angel
Roee Angel

Reputation: 201

How to correctly implement the pause function in a React component using Howler.js?

I am currently working on a project where I have a toggle button for play and pause using Howler.js library. While the onpause event is firing, the sound continues to play even though the pause function is being called. Here's a sample code of what I have implemented so far:

export default (props) => {
  let [soundState, setSoundState] = useState({ state: 'off' })
  let [soundId, setSoundId] = useState(null)
  let [soundSeek, setSoundSeek] = useState(null)
  var sound = new Howl({
    src: [props.url],
    html5: true,
    volume: 1,
    myMusicID: '',
    saveSeek: null,
    onpause: () => {
      console.log('pause', soundId)
    }
  })

  const onPlayHandle = () => {
    setSoundState({ state: 'playing' })
    let id = sound.play()
    setSoundId(id)
    sound.seek(soundSeek, soundId)
  }
  const onPauseHandle = () => {
    console.log('onPauseHandle', soundId)
    sound.pause(soundId)
    setSoundSeek(sound.seek(soundId))
  }
 
}

I would appreciate any help or suggestions on how to correctly implement the pause function so that it stops the sound from playing. Thank you.

Upvotes: 2

Views: 359

Answers (1)

lissettdm
lissettdm

Reputation: 13078

Every time your component is renderer a new Howl instance is created. You need to use useRef to keep the instance reference:

const soundRef = useRef(new Howl({
    src: ["http://listen.vo.llnwd.net/g3/prvw/6/5/8/3/1/2255913856.mp3"],
    html5: true,
    volume: 1,
    myMusicID: "",
    saveSeek: null,
    onpause: () => {
      console.log("pause", soundId);
    }
  }));
const sound = soundRef.current;

Upvotes: 2

Related Questions